在阿里云的oss中,我們可以設置 Content-Disposition 來決定文件的是預覽還是下載。
Content-Disposition 設置為 attachment 的話,生成的url就是直接下載的。
最近在工作中,遇到前端需要同時支持附件的預覽和下載。但是又不可能為這個需求,去上傳兩個相同的文件,分別將Content-Disposition 設置為 attachment 及 inline ,在官方文檔中,生成下載文件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之前的 ? 換成 & 。
原本生成的格式會是
需要替換成
然后就可以愉快的根據設置不同的 disposition 入參("attachment" 及 "inline" )來選擇性生成預覽或者下載的鏈接了。