文件上传Content-disposition中Attachment和inline的区别

编程知识 更新时间:2023-04-05 07:18:49

在日常开发中文件上传需要设置content-disposition类型,是下载还是内嵌显示。如我用阿里云或者京东云上传图片,我需要打开连接是直接显示图片,而导出excel文件我希望直接下载文件那么content-disposition设置就不一样。

java web中下载文件时,我们一般设置Content-Disposition告诉浏览器下载文件的名称,是否在浏览器中内嵌显示.
Content-disposition: inline; filename=1502849449726.jpg表示浏览器内嵌显示一个文件

Content-disposition: attachment; filename=1502849449726.xlsx表示会下载文件,如火狐浏览器中


案例:图片上传设置content-dispition

//指定该Object文件类型,默认值application/octet-stream
objectMetadata.setContentType(getContentType(fileName));
/**
 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
 * @param fileName 文件名
 * @return 文件的contentType
 */
public static  String getContentType(String fileName){
	//文件名后缀
	String fileExtension = fileName.substring(fileName.lastIndexOf("."));
	if(".bmp".equalsIgnoreCase(fileExtension)) {
		return "image/bmp";
	}
	if(".gif".equalsIgnoreCase(fileExtension)) {
		return "image/gif";
	}
	if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)  || ".png".equalsIgnoreCase(fileExtension) ){
		return "image/jpeg";
	}
	if(".html".equalsIgnoreCase(fileExtension)){
		return "text/html";
	}
	if(".txt".equalsIgnoreCase(fileExtension)){
		return "text/plain";
	}
	if(".vsd".equalsIgnoreCase(fileExtension)){
		return "application/vnd.visio";
	}
	if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
		return "application/vnd.ms-powerpoint";
	}
	if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
		return "application/msword";
	}
	if(".xml".equalsIgnoreCase(fileExtension)) {
		return "text/xml";
	}
	return "image/jpeg";
}
备注:

这样在浏览器访问上传图片地址就是直接打开图片而不是下载图片。默认头文件类型为application/octet-stream,故必须针对可内嵌显示的类型,如上诉代码中列表出的那么多类型。




更多推荐

文件上传Content-disposition中Attachment和inline的区别

本文发布于:2023-04-05 07:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/94da162a9c8f2846557c06f07a04fcb2.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件上传   区别   Content   disposition   Attachment

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45504文章数
  • 14阅读数
  • 0评论数