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

默认上传时未指定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");

 

oss sdk实现方式

pom引入版本

<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.9.1</version>
</dependency>

sdk代码实现

import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.ResponseHeaderOverrides;


        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(aliyunConfig.getBucket(), key);
        generatePresignedUrlRequest.setExpiration(expires);
        
        ResponseHeaderOverrides responseHeaderOverrides = new ResponseHeaderOverrides();
        String contentType = MediaTypeFactory.getMediaType(key).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
        responseHeaderOverrides.setContentType(contentType.toUpperCase());
        generatePresignedUrlRequest.setResponseHeaders(responseHeaderOverrides);
        com.aliyun.oss.OSS oss = null;//替换为自己初始化的客户端
        return oss.generatePresignedUrl(generatePresignedUrlRequest).toString();//此处是域名内网地址,注意需要转换为外网地址

 

 

 

分享一个淘宝、京东、拼多多、饿了么、美团、抖音等等买东西后真实返钱小技巧,

打车、外卖领券,充值话费95折好像也可以

使用教程用微信扫下方二维码查看详细说明

 

posted @ 2023-06-01 10:19  Binz  阅读(3930)  评论(6编辑  收藏  举报