响应传输文件

发布于 2024-08-13 10:08:13 字数 820 浏览 6 评论 0原文

我有以下代码,当用户单击下载链接时向他们传送文件。出于安全目的,我不能直接链接到文件,因此设置它是为了解码 url 并传输文件。

它已经工作正常了一段时间,但最近我开始遇到问题,文件将开始下载,但没有迹象表明文件有多大。

因此,当下载应该停止时,它却没有。

该文件大约有 99mb,但当我下载它时,浏览器一直在下载超过 100mb 的文件。我不知道它正在下载什么,但如果我不取消它,它就不会停止。

所以,我的问题是,是否有 TransmitFile 的替代方案或确保发送文件大小以便在正确的时间停止的方法?

这是代码:

string filename = Path.GetFileName(url); 
context.Response.Buffer = true; 
context.Response.Charset = ""; 
context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
context.Response.ContentType = "application/x-rar-compressed"; 
context.Response.AddHeader("content-disposition", "attachment;filename=" + filename);   
context.Response.TransmitFile(context.Server.MapPath(url));
context.Response.Flush(); 

我不想使用 WriteFile 因为我不想将整个文件加载到内存中,因为它太大了。

谢谢。

I have the following code delivering a file to users when they click on a download link. For security purposes I can't just link directly to the file so this was set up to decode the url and transmit the file.

It has been working fine for a while but recently I started having problems where the file will start downloading but there's no indication of how large the file is.

Because of this when the download should stop, it doesn't.

The file is about 99mb but when I download it, the browser just keeps downloading way beyond 100mb. I don't know what it's downloading but if I don't cancel it, it doesn't stop.

So, my question is, is there either an alternative to TransmitFile or a way to make sure the size of the file is sent also so that it stops at the right time?

Here is the code:

string filename = Path.GetFileName(url); 
context.Response.Buffer = true; 
context.Response.Charset = ""; 
context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
context.Response.ContentType = "application/x-rar-compressed"; 
context.Response.AddHeader("content-disposition", "attachment;filename=" + filename);   
context.Response.TransmitFile(context.Server.MapPath(url));
context.Response.Flush(); 

I don't want to use WriteFile because I don't want to load the entire file into memory since it's so large.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二货你真萌 2024-08-20 10:08:13

我想我已经找到答案了。

我添加了以下代码,现在,至少对我来说,它报告了正确的文件大小并按预期工作。

FileInfo OutFile = new FileInfo(context.Server.MapPath(url));
long filesize = OutFile.Length; 
....
context.Response.AddHeader("Content-Length", filesize.ToString());

I think I've found the answer.

I added the following code and now, at least for me, it is reporting the correct file size and working as expected.

FileInfo OutFile = new FileInfo(context.Server.MapPath(url));
long filesize = OutFile.Length; 
....
context.Response.AddHeader("Content-Length", filesize.ToString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文