AWS S3:使用"response-content-disposition"强制下载文件 [英] AWS S3: Force File Download using 'response-content-disposition'

查看:683
本文介绍了AWS S3:使用"response-content-disposition"强制下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下几行生成签名的URL,浏览器重定向到该URL以从S3下载文件.

Few lines(below) generate signed URL to which browser is redirected to download a file from S3.

当内容类型设置为八位位流时,我面临着一个众所周知的Chrome无法从S3下载pdf文件的问题.

I am facing well known issue of Chrome not downloading pdf files from S3 when content type is set as Octet Stream.

解决方案是强制chrome下载文件,而不是尝试读取/打开文件.

The solution is to force chrome to download file instead of trying to read/open it.

我尝试添加'response-content-disposition'来签名和URL,但这没有用.

I tried adding 'response-content-disposition' to sign as well as URL, but it didn't work.

要生成url时,如何使用"response-content-disposition"标头?

How to use 'response-content-disposition' header when url is to be generated?

    String codedFilename=  EncodingUtil.urlEncode(bucketPath,'UTF-8');

    String stringtosign = 'GET\n\n\n'+Lexpires+'\n/'+bucketName+'/'+codedFilename;

    String signed = make_sig(stringtosign); 

    String codedsigned = EncodingUtil.urlEncode(signed,'UTF-8');

    String url = serverURL+'/'+bucketName+'/'+codedFilename+'?AWSAccessKeyId='+awskey+'&Expires='+Lexpires+'&Signature='+codedsigned;

注意:-这是salesforce-apex语法.

Note:- This is salesforce-apex syntax.

推荐答案

    String codedFilename=  EncodingUtil.urlEncode(bucketPath,'UTF-8');

    String stringtosign = 'GET\n\n\n'+Lexpires+'\n/'+bucketName+'/'+codedFilename+'?response-content-disposition=attachment; filename=abc.doc';

    String signed = make_sig(stringtosign); 

    String codedsigned = EncodingUtil.urlEncode(signed,'UTF-8');

    String url = serverURL+'/'+bucketName+'/'+codedFilename+'?response-content-disposition='+EncodingUtil.urlEncode('attachment; filename=abc.doc','UTF-8')+'&AWSAccessKeyId='+awskey+'&Expires='+Lexpires+'&Signature='+codedsigned;

来源:无法覆盖s3中的内容处置标头

如果文档的内容类型为应用程序/八位字节流",则Chrome存在问题(在这种情况下为pdf).但是,如果内容类型为二进制/八位字节流",则可以使用chrome.

Chrome has problem if content type is 'application/octet-stream' for a document(pdf int this case). However chrome is OK if content type is 'binary/octet-stream'.

如果在上载时未设置nothig,则S3最好将下载的Content-Type默认设置为"binary/Octet-stream".

Thankfully S3 defaults Content-Type of download to 'binary/Octet-stream' if nothig is set at the time of upload.

我的建议:- 如果需要在上载时不知道内容类型的情况下将"any"类型的文件保存到S3,只需不要设置它或将其设置为"binary/Octet-stream".这样,Chrome会显示警告,但文件已下载.

My Advice:- If one needs to files of 'any' type to S3 without knowing content type at the time of upload, simply do not set it or set it to 'binary/Octet-stream'. This way Chrome will show warning but file is downloaded.

这篇关于AWS S3:使用"response-content-disposition"强制下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆