方案1
通过nginx加响应头,自己在下载地址后面添加参数 &attname=filename
location / {
proxy_pass ;
if ($query_string ~* ^(.*)attname=([^&]+)$) {
add_header Content-Disposition "attachment;filename=$arg_attname";
}
}
缺点:下载速度取决于nginx部署的服务器带宽,影响用户体验
于是乎有了
方案2
通过查看oss获取文件下载地址的源代码:
@Override
public URL generatePresignedUrl(String bucketName, String key, Date expiration) throws ClientException {
return generatePresignedUrl(bucketName, key, expiration, );
}
@Override
public URL generatePresignedUrl(String bucketName, String key, Date expiration, HttpMethod method)
throws ClientException {
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key);
(expiration);
(method);
return generatePresignedUrl(request);
}
@Override
public URL generatePresignedUrl(GeneratePresignedUrlRequest request) throws ClientException {
assertParameterNotNull(request, "request");
if (() == null) {
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("MustSetBucketName"));
}
ensureBucketNameValid(());
if (() == null) {
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("MustSetExpiration"));
}
String url;
if (().getSignatureVersion() != null && ().getSignatureVersion() == SignVersion.V2) {
url = (request, (), (), endpoint);
} else {
url = (request, (), (), endpoint);
}
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new ClientException(e);
}
}
发现最终调用的都是generatePresignedUrl(GeneratePresignedUrlRequest request)
方法
于是乎研究GeneratePresignedUrlRequest
找到了重写响应头的方法
/**
* Sets the response headers to override.
*
* @param responseHeaders
* The response headers to override.
*/
public void setResponseHeaders(ResponseHeaderOverrides responseHeaders) {
= responseHeaders;
}
然后测试以下代码
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKETNAME, key);
(new Date(() + 3600 * 1000 * 24 * 7));
();
ResponseHeaderOverrides header = new ResponseHeaderOverrides();
("attachment;filename=" + fileName);
(header);
URL url = (request);
返回的url中多了 &response-content-disposition=attachment%3Bfilename%3DfilName
测试链接果然可以重命名