Download file to client PC in ASP.NET using VB.NET

白昼怎懂夜的黑 提交于 2019-12-13 00:51:33

问题


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.

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.

(For reference: I want to implement the functionality similar to VSS.)


回答1:


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:

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.



来源:https://stackoverflow.com/questions/14020113/download-file-to-client-pc-in-asp-net-using-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!