我正在使用下面的示例代码来编写和下载内存流到C#中的文件.
MemoryStream memoryStream = new MemoryStream();
TextWriter textWriter = new StreamWriter(memoryStream);
textWriter.WriteLine("Something");
byte[] bytesInStream = new byte[memoryStream.Length];
memoryStream.Write(bytesInStream, 0, bytesInStream.Length);
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition",
"attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytesInStream);
Response.End();
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
指定的参数超出了有效值的范围.
参数名称:offset
可能是什么原因?
在我的 javascript 客户端中,我使用 fetch 调用服务器来检索服务器生成的文件。我正在使用以下客户端代码:
var _url = "";
var initParms = {
method: "GET",
mode: 'cors'
}
fetch(_url, initParms)
.then(response => {
if(response.ok){
alert(response.headers.get("content-disposition"));
return response.blob();
}
throw new Error("Network response was not OK.");
})
.then(blob => {
var url = new URL.createObjectURL(blob);
})
Run Code Online (Sandbox Code Playgroud)
这实际上工作得很好。但是,服务器会为该文件生成一个文件名,并将其作为 content-disposition 标头的一部分包含在响应中。
我需要使用服务器生成的文件名将此文件保存到用户的机器上。在 Postman 中,我实际上可以看到响应的内容处置标头设置为:Content-Disposition: attachment;filename=myfilename.txt。
我试图从响应中读取内容配置(请参阅我的 js 代码中的警报),但我总是得到 null(即使相同的响应显示了 Postman 中的内容配置)。
难道我做错了什么?有没有办法使用 fetch 响应来检索文件名?有没有更好的方法从服务器获取文件名和文件?
PS 这是我返回文件的服务器端代码:
控制器动作
public IHttpActionResult GetFile(){
return new FileResult("myfilename.txt","Hello World!");
}
Run Code Online (Sandbox Code Playgroud)
文件结果类
public class FileResult : IHttpActionResult …Run Code Online (Sandbox Code Playgroud) 首先,我很确定这不是重复,因为我已经在StackOverflow和其他地方研究了这个主题很长一段时间.已经提出了类似的问题,但没有人得到满意的回答.
过去的相关(但不完全相同)问题:
我也完全了解使用HTTP标头中的文件名完全没必要的mod_rewrite技巧.但我们假设这不是一个选择.
大多数现代浏览器(IE9 +,Firefox,Chrome)在下载名称中包含非ASCII字符的文件时都支持RFC2231/5987.在这些情况下,以下PHP代码就像一个魅力:
header("Content-Disposition: attachment; " .
"filename*=UTF-8''" . rawurlencode($filename));
Run Code Online (Sandbox Code Playgroud)
IE <= 8不了解RFC2231/5987,但以下代码大部分时间都有效.由于每个浏览器都试图在某种程度上模拟IE,这也适用于许多其他浏览器,例如Firefox.
header("Content-Disposition: attachment; " .
'filename="' . rawurlencode($filename) . '"');
Run Code Online (Sandbox Code Playgroud)
同时,Chrome <11和Safari <6似乎更喜欢以下内容,尽管它将非ASCII字符直接放在标题中.
header("Content-Disposition: attachment; filename=" . $filename);
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.
但是,当谈到Android的默认浏览器应用程序时,一切都崩溃了.(到目前为止,我已经在姜饼,冰淇淋三明治和果冻豆中进行了测试.)
如果您给它标准的RFC2231/5987处理,默认浏览器完全忽略它并尝试从URL的最后部分猜测文件名.
如果你给它通常的非标准(IE <= 8)处理,默认浏览器会尝试将文件名解释为ISO-8859-1,导致无法理解的字符混乱,或者它会以静默方式丢弃所有非ASCII字符.版本之间的确切行为有所不同,但无论如何,很明显Android的默认浏览器也不支持rawurlencode()格式.
如果将原始文件名放在标题中,则会发生同样的情况.
这通常不是第三方浏览器的问题,例如Firefox for Android,Dolphin Browser和Boat Browser.默认浏览器应用程序是唯一一直无法理解UTF-8文件名的应用程序.
也许这最终在Android的最新版本中得到了修复,或者可能会在下一个版本中修复.但这不是我的问题.我需要这个在现有设备中工作,并且仍然有数百万个Gingerbread和ICS设备.
我已经阅读了错误报告,我已经阅读了投诉,我已经阅读了很多关于这个问题的内容.到目前为止,我一直无法找到任何实际有效的编码方案.
如果有人知道如何在**标头中编码非ASCII文件名**(例如????????????.jpg)并让Android默认浏览器识别它,请分享!我不在乎它是多么hacky或非标准.我不关心是否需要针对每个Android版本进行自定义. Content-Disposition
不幸的是,到目前为止,我还没有收到任何能够解决上述问题的答案.所以赏金到期无人认领.请不要回答,除非您确实知道如何以ICS之前的Android浏览器识别的方式编码非欧洲混合语言文件名,或者您有确凿的证据表明这是不可能的.
我正在编写一个简单的文件下载servlet,我无法获得正确的文件名.尝试URLEncoding和MimeEncoding文件名,如现有答案所示,但没有一个工作.
以下代码段中的fileData对象包含mime类型,byte []内容和文件名,至少需要ISO-8859-2字符集,ISO-8859-1是不够的.
如何让浏览器正确显示下载的文件名?
以下是文件名的示例:árvíztűrőtükörfúrógép.xls,结果如下:árvíztqrptükörfúrógép.xls
protected void renderMergedOutputModel(Map model, HttpServletRequest req, HttpServletResponse res) throws Exception {
RateDocument fileData = (RateDocument) model.get("command.retval");
OutputStream out = res.getOutputStream();
if(fileData != null) {
res.setContentType(fileData.getMime());
String enc = "utf-8"; //tried also: ISO-8859-2
String encodedFileName = fileData.getName();
// also tried URLencoding and mime encoding this filename without success
res.setCharacterEncoding(enc); //tried with and without this
res.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
res.setContentLength(fileData.getBody().length);
out.write(fileData.getBody());
} else {
res.setContentType("text/html");
out.write("<html><head></head><body>Error downloading file</body></html>"
.getBytes(res.getCharacterEncoding()));
}
out.flush();
}
Run Code Online (Sandbox Code Playgroud) 我正在使用Google App Engine Blobstore来存储一系列文件类型(PDF,XLS等),并且我正在尝试找到一种机制,通过该机制可以使用上传文件的原始文件名(存储在blob_info中)来命名下载的文件,即用户在保存对话框中看到'some_file.pdf'而不是'very_long_db_key.pdf'.
我在文档中看不到任何允许这样的内容:
http://code.google.com/appengine/docs/python/blobstore/overview.html
我在其他帖子中看到了一些提示,你可以使用blob_info中的信息来设置content-disposition头.这是实现理想目标的最佳方法吗?
我有一个 S3 存储桶,其中包含 PDF 文件作为对象,并且所有文件都是私有的。我以编程方式创建一个 S3 预签名 URL 来获取该对象。效果很好。现在,我希望它可以以 PDF 形式预览。每个对象都已经有一个Content-Type设置为 的标头application/pdf。现在,如果我将response-content-disposition标头设置为查询参数,它会被设置但不会覆盖已经存在的Content-disposition标头,而是创建一个新标头。如果我Content-Disposition在 S3 对象的元数据中设置标头,而不是将其作为查询参数添加到 S3 预签名 URL 中,它仍然显示 2 个标头。这是 AWS S3 端的某种错误吗?
以下是响应标头的屏幕截图以供参考。
任何帮助都感激不尽。谢谢。
amazon-s3 content-disposition amazon-web-services node.js pre-signed-url
我们使用此代码生成请求并设置下载文件名:
var request = new GetPreSignedUrlRequest()
.WithBucketName(S3BucketName)
.WithExpires(requestExpirationTime)
.WithKey(file.S3Key)
.WithResponseHeaderOverrides(
new ResponseHeaderOverrides()
.WithContentDisposition("attachment; filename=\"Unicode FileName ? Test.txt\""));
Run Code Online (Sandbox Code Playgroud)
这会生成以下链接:
/s3path?AWSAccessKeyId=xxxx&Expires=1377199946&response-content-disposition=attachment%3B%20filename%3D"Unicode%20FileName%20?%20Test.txt"&Signature=xxxxx
Run Code Online (Sandbox Code Playgroud)
这给出了这个错误:
<Error>
<Code>InvalidArgument</Code>
<Message>
Header value cannot be represented using ISO-8859-1.
</Message>
<ArgumentValue>attachment; filename="Unicode ? filename.txt"</ArgumentValue>
<ArgumentName>response-content-disposition</ArgumentName>
<RequestId>368BD60502854514</RequestId>
<HostId>
BiUUYp4d9iXfK68jKVxWZEp25m5je166M0ZY1VmoPk9pN9A69HLHcff6WIVLWk1B
</HostId>
</Error>
Run Code Online (Sandbox Code Playgroud)
我们如何在response-content-disposition头中使用非ISO-8859-1字符,例如unicode?
我已经在SO上阅读了几个相关的问题,但没有设法找到一个有效的解决方案.
我有一个带有这个简化代码的Flask服务器:
app = Flask(__name__)
api = Api(app)
class SendMailAPI(Resource):
def post(self):
print request.files
return Response(status=200)
api.add_resource(SendMailAPI, '/')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
Run Code Online (Sandbox Code Playgroud)
然后在客户端:
# coding:utf-8
import requests
eng_file_name = 'a.txt'
heb_file_name = u'?.txt'
requests.post('http://localhost:5000/', files={'file0': open(eng_file_name, 'rb')})
requests.post('http://localhost:5000/', files={'file0': open(heb_file_name, 'rb')})
Run Code Online (Sandbox Code Playgroud)
当发送带有非utf-8文件名的第一个请求时,服务器接收带有文件的请求并打印ImmutableMultiDict([('file0', <FileStorage: u'a.txt' (None)>)]),但是当发送带有utf-8文件名的文件时,服务器似乎在打印时没有收到该文件ImmutableMultiDict([]).
我正在使用请求,2.3.0但问题并没有解决最新版本(2.8.1),Flask版本0.10.1和Flask-RESTful版本0.3.4.
我已经完成了一些requests代码挖掘并且请求似乎已发送正常(即使用该文件),并且我在发送之前打印了请求,并且看到文件名确实编码为RFC2231:
--6ea257530b254861b71626f10a801726
Content-Disposition: form-data; name="file0"; filename*=utf-8''%D7%90.txt
Run Code Online (Sandbox Code Playgroud)
总结一下,我不完全确定问题是否在于requests没有正确地将文件附加到请求,或者是否Flask存在拾取具有根据RFC2231编码的文件名的文件的问题.
更新:在requestsGitHub中遇到过这个问题:https://github.com/kennethreitz/requests/issues/2505
我们的CMS接受名称中包含国家字符的文件,并将它们存储在服务器上,没有任何问题.但这种方法有多糟糕?例如,是否可以使用希伯来语,阿拉伯语或任何其他非拉丁字母的语言存储文件名?是否有标准的既定方法来处理这些?
我想通过这种方式下载音乐文件:
require 'open-uri'
source_url = "http://soundcloud.com/stereo-foo/cohete-amigo/download"
attachment_file = "test.wav"
open(attachment_file, "wb") do |file|
file.print open(source_url).read
end
Run Code Online (Sandbox Code Playgroud)
在该示例中,我想将"Test.wav"更改为真实文件名(例如JDownloader程序).
编辑:我不是指临时文件,我的意思是像Jdownloader这样的网络存储文件得到:"Cohete Amigo - Stereo Foo.wav"
谢谢你的阅读
更新:
我试过这个来存储这个名字:
attachment_file = File.basename(open(source_url))
Run Code Online (Sandbox Code Playgroud)
我认为这没有任何意义,但我不知道如何做到这一点,抱歉.