vb.net 使用VB.NET在ASP.NET中将文件下载到客户端PC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14020113/
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
Download file to client PC in ASP.NET using VB.NET
提问by NK-
I am developing a website that would be accessible only within our organisation.
我正在开发一个只能在我们组织内部访问的网站。
I want to implement a functionality in which the client will download a file (Visio File *.vsd)from the server and save it to any location.
我想实现一个功能,其中客户端将从(Visio File *.vsd)服务器下载文件并将其保存到任何位置。
I came across a solution:
我遇到了一个解决方案:
dim wc as new WebClient ()
wc.downloadFile(src,dest)
However, this solution doesn't prompt the save as dialog box (which I want in my application). Also I should know the path on the client's PC where he has saved the file, so that the path can be saved in a database.
但是,此解决方案不会提示另存为对话框(我希望在我的应用程序中使用)。此外,我应该知道他保存文件的客户端 PC 上的路径,以便可以将路径保存在数据库中。
(For reference: I want to implement the functionality similar to VSS.)
(供参考:我想实现类似于VSS的功能。)
回答by Darin Dimitrov
In ASP.NET if you want to stream a file to the client and have the Save As dialog prompt the user to select a location you will have to set the correct Content-Type and Content-Disposition response headers and then write the file directly to the response stream:
在 ASP.NET 中,如果要将文件流式传输到客户端并让“另存为”对话框提示用户选择位置,则必须设置正确的 Content-Type 和 Content-Disposition 响应标头,然后将文件直接写入响应流:
For example:
例如:
protected void SomeButton_Click(object sender, EventArgs e)
{
// TODO: adjust the path to the file on the server that you want to download
var fileToDownload = Server.MapPath("~/App_Data/someFile.pdf");
Response.ContentType = "application/octet-stream";
var cd = new ContentDisposition();
cd.Inline = false;
cd.FileName = Path.GetFileName(fileToDownload);
Response.AppendHeader("Content-Disposition", cd.ToString());
byte[] fileData = System.IO.File.ReadAllBytes(fileToDownload);
Response.OutputStream.Write(fileData, 0, fileData.Length);
}
Now when this code executes, the file will be sent to the client browser which will prompt to Save it on a particular location on his computer.
现在,当此代码执行时,文件将发送到客户端浏览器,客户端浏览器将提示将其保存在他计算机上的特定位置。
Unfortunately for security reasons you have no way of capturing the directory in which the client choose to store the file on his computer. This information never transits over the wire and you have no way of knowing it inside your ASP.NET application. So you will have to find some other way of obtaining this information, such as for example asking the client to enter it in some text box or other field.
不幸的是,出于安全原因,您无法捕获客户端选择在其计算机上存储文件的目录。此信息永远不会通过网络传输,您无法在 ASP.NET 应用程序中了解它。因此,您必须找到其他一些获取此信息的方法,例如要求客户在某个文本框或其他字段中输入它。

