为什么浏览器对有些图片是直接预览打开,对有些图片是直接下载?—— 原由就在Content-Type响应头上;
Content-Type响应头的作用: Content-Type 用于向接收方说明传输资源的媒体类型,从而让浏览器用指定码表去解码。
由于浏览器的限制,当上传文件时,设置header为application/octet-stream时,浏览器打开链接会默认进行下载而不是在浏览器中加载文件,所以如果想要文件时直接打开,上传时则不要设置application/octet-stream
常见的媒体格式类型如下:
text/html : HTML格式 text/plain :纯文本格式 text/xml : XML格式 image/gif :gif图片格式 image/jpeg :jpg图片格式 image/png:png图片格式
以application开头的媒体格式类型:
application/xhtml+xml :XHTML格式 application/xml: XML数据格式 application/atom+xml :Atom XML聚合格式 application/json: JSON数据格式 application/pdf:pdf格式 application/msword : Word文档格式 application/octet-stream : 二进制流数据(如常见的文件下载) application/x-www-form-urlencoded :默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
// 上传参数中指定
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.bucket(bucket)
.object(objectName)
// 上传时指定对应对ContentType
.contentType(ViewContentType.getContentType(objectName))
.stream(multipartFile.getInputStream(), multipartFile.getSize(), 1024*1024*5+1)
.build();
//列举部分图片的Content-Type
public enum ViewContentType {
DEFAULT("default","application/octet-stream"),
JPG("jpg", "image/jpeg"),
TIFF("tiff", "image/tiff"),
GIF("gif", "image/gif"),
JFIF("jfif", "image/jpeg"),
PNG("png", "image/png"),
TIF("tif", "image/tiff"),
ICO("ico", "image/x-icon"),
JPEG("jpeg", "image/jpeg"),
WBMP("wbmp", "image/vnd.wap.wbmp"),
FAX("fax", "image/fax"),
NET("net", "image/pnetvue"),
JPE("jpe", "image/jpeg"),
RP("rp", "image/vnd.rn-realpix");
private String prefix;
private String type;
public static String getContentType(String prefix){
if(StrUtil.isEmpty(prefix)){
return DEFAULT.getType();
}
prefix = prefix.substring(prefix.lastIndexOf(".") + 1);
for (ViewContentType value : ViewContentType.values()) {
if(prefix.equalsIgnoreCase(value.getPrefix())){
return value.getType();
}
}
return DEFAULT.getType();
}
ViewContentType(String prefix, String type) {
this.prefix = prefix;
this.type = type;
}
public String getPrefix() {
return prefix;
}
public String getType() {
return type;
}
}
public String shareObjectStream(String bucket, String objectKey) throws OssException {
Map<String,String> headers = new HashMap<>();
headers.put("response-content-type", "application/octet-stream");
String url = getMinioClient().getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucket)
.object(objectKey)
.expiry(60 * 60 * 24)
.extraQueryParams(headers)
.build());
return url;
}