獲取阿里雲OSS文件下載地址時,設置預覽或下載


在阿里雲的oss中,我們可以設置 Content-Disposition 來決定文件的是預覽還是下載。
Content-Disposition 設置為 attachment 的話,生成的url就是直接下載的。

最近在工作中,遇到前端需要同時支持附件的預覽和下載。但是又不可能為這個需求,去上傳兩個相同的文件,分別將Content-Disposition 設置為 attachmentinline ,在官方文檔中,生成下載文件url時,也沒看到有什么入參能夠區分這兩種情況。

其實,我們通過設置response-content-disposition 的方式,就可以達到這個目的。

//上略
Date expiration = new Date(new Date().getTime() + 1800 * 1000);
GeneratePresignedUrlRequest generatePresignedUrlRequest;
String attachment = "?response-content-disposition=" + disposition;
String attachmentEncoder = encoder(attachment);

key = key + attachment;

generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ossProperties.getBucketName(), key);
generatePresignedUrlRequest.setExpiration(expiration);
url = client.generatePresignedUrl(generatePresignedUrlRequest).toString().replace(attachmentEncoder + "?", attachment + "&");
// 下略

    private String encoder(String s) throws UnsupportedEncodingException {
        String encoder = URLEncoder.encode(s, "UTF-8");
        encoder = encoder.replaceAll("\\+", "%20");
        encoder = encoder.replaceAll("\\*", "%2A");
        return encoder;
    }

response-content-disposition放到文件的key中一起去簽名。

最后要做一次替換是因為要把自動生成的,Expires之前的 ? 換成 & 。
原本生成的格式會是

http://1.1.1.1:9999/bucketName/123/a.pdf%3Fresponse-content-disposition%3Dattachment?Expires=1592402977&OSSAccessKeyId=a&Signature=b

需要替換成

http://1.1.1.1:9999/bucketName/123/a.pdf?response-content-disposition=attachment&Expires=1592402977&OSSAccessKeyId=a&Signature=b

然后就可以愉快的根據設置不同的 disposition 入參("attachment""inline" )來選擇性生成預覽或者下載的鏈接了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM