阿里云OSS访问图片自动直接下载问题,改成能预览的预览,不能预览的才下载

发布时间 2023-06-01 10:25:58作者: Binz

默认上传时未指定contentType,统一都为application/octet-stream 

访问就会下载,例如:https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?response-content-type=APPLICATION/OCTET-STREAM

如果指定为真实的媒体类型,浏览器能打开就会直接预览,例如:https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?response-content-type=IMAGE/JPEG

 

Java获取文件真实的contentType:注意,经过测试,一定要转大写,不然会失效

import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import java.net.URLEncoder;

String url = "https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg";
String contentType = MediaTypeFactory.getMediaType(url).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
String url = url + "?response-content-type="+URLEncoder.encode(contentType.toUpperCase(),"UTF-8");