C# Response.TransmitFile 的替代方案,用于通过 HTTP 传输文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1155183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:31:58  来源:igfitidea点击:

Alternative to Response.TransmitFile for transferring files via HTTP

c#asp.nethttpwebrequest

提问by mancmanomyst

I'm working on a ASP.NET website that allows users to download files.

我正在开发一个允许用户下载文件的 ASP.NET 网站。

Previously the files were stored on the same server as the website so we could do:

以前,这些文件与网站存储在同一台服务器上,因此我们可以执行以下操作:

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
Response.AddHeader("Content-Length", response.ContentLength.ToString());
Response.ContentType = "application/octet-stream";
Response.TransmitFile(path);
Response.End();

However, now some of the files are stored on a seperate server. I can verify that the files exist using

但是,现在一些文件存储在单独的服务器上。我可以使用以下方法验证文件是否存在

WebRequest request = WebRequest.Create(absolute-url);
WebResponse response = request.GetResponse();

But how can I facilitate the transfer as TransmitFile requires a virtual path not a url?

但是我怎样才能促进传输,因为 TransmitFile 需要一个虚拟路径而不是一个 url?

I need the users to be able to choose where to Save the file as with a normal web download

我需要用户能够选择将文件保存为普通 Web 下载的位置

What's the best way to do this?

做到这一点的最佳方法是什么?

回答by David

  1. Could you redirect the user to the URL on the other server?
  2. You could proxy the request to the other server. When you call "GetResponse", take the stream and write its contents out to your Response object.
  1. 您能否将用户重定向到另一台服务器上的 URL?
  2. 您可以将请求代理到另一台服务器。当您调用“GetResponse”时,获取流并将其内容写入您的 Response 对象。

回答by Keith Adler

You could map the drives of the remote servers as shares and then use TransmitFile. If the servers don't have line of sight you could enable WebDAV on the remote server(s) and then map them to a physical path and use TransmitFile.

您可以将远程服务器的驱动器映射为共享,然后使用 TransmitFile。如果服务器没有视线,您可以在远程服务器上启用 WebDAV,然后将它们映射到物理路径并使用 TransmitFile。

回答by Keith Adler

You can't use TransferFile for remote file. But you can use WriteFile for this.

您不能将 TransferFile 用于远程文件。但是您可以为此使用 WriteFile。

回答by TrystanC

If you can get the response stream via a web request you should be able to copy the stream to your output stream as per this snippet:

如果您可以通过 Web 请求获取响应流,您应该能够按照以下代码段将流复制到输出流:

while ((read = stream.Read(buffer, offset, chunkSize)) > 0)    
{

    Response.OutputStream.Write(buffer, 0, read);
    Response.Flush();
}