gpt4 book ai didi

asp.net - 文件名包含空格的 TransmitFile

转载 作者:行者123 更新时间:2023-12-02 14:08:58 28 4
gpt4 key购买 nike

在 C# ASP.Net 网站中,将文件传输到我正在使用的客户端

String file_path = Server.MapPath("~/files/"+file_name); 
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + file_Name);
HttpContext.Current.Response.TransmitFile(file_path);
HttpContext.Current.Response.End();

它工作正常,但是当文件名包含任何空格时,下载的文件的名称仅限于第一个单词。例如:如果我的文件名是 "This is demo.txt" 那么下载的文件名将变为 "This" 且没有扩展名。因此下载它的用户无法识别其类型。
如何避免文件名包含空格的情况发生?

我尝试使用

String file_path = "'"+Server.MapPath("~/files/"+file_name)+"'";

但是没有成功。

我也不可能替换(用“_”或“-”)或删除服务器上存在的文件名中存在的所有空格。

最佳答案

您应该将文件名括在引号中。

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + file_Name + "\"");

如果您使用的是 VS2015 或更高版本,您可以通过字符串插值使其变得更整洁:

HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=\"{file_Name}\"");

此外, header 中的文件名不必与文件名相同。 header 中的文件名仅是给用户的建议。

有关完整详细信息,请参阅 RFC 6266 “超文本传输​​协议(protocol) (HTTP) 中内容处置 header 字段的使用”,特别是关于哪些字符可能会导致文件名出现问题。

关于asp.net - 文件名包含空格的 TransmitFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12424066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com