How to send a file to a client so a Download dialog will open?

会有一股神秘感。 提交于 2020-01-04 07:18:16

问题


I have a file, say a PDF on my website and when a user visits a page I want to display a download dialog for the pdf on page load or a button click.

I did a google search and I found two ways to do this but wondering what is the accepted way of doing this? I am currently doing this

string pdfPath = MapPath("mypdf.pdf");
Response.ContentType = "Application/pdf";


Response.AppendHeader( "content-disposition",
        "attachment; filename=" + name );
Response.WriteFile(pdfPath);
Response.End();

(Code was based off code from http://aspalliance.com/259, also found code from http://www.west-wind.com/weblog/posts/76293.aspx)


回答1:


Your code, will display the file to the user perfectly. But they will have to use the "Save As" option to actually save it.

If you wish to present the "Save Dialog" to the user, try the following:

string pdfPath = MapPath("mypdf.pdf");
Response.ContentType = "Application/pdf";
Response.AppendHeader("content-disposition",
        "attachment; filename=" + pdfPath );
Response.TransmitFile(pdfPath);
Response.End();

This of course assumes the file actually exists on the server and is not being dynamically generated.




回答2:


This code will Send Any file to directly on client Browser

    Response.ContentType = "application/pdf";
    Response.WriteFile(PathToFile);
    Response.Flush();


来源:https://stackoverflow.com/questions/3252135/how-to-send-a-file-to-a-client-so-a-download-dialog-will-open

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