2014-09-30 443 views
0

在我的应用程序中,我想给用户下载PDF文件的选项。在我的代码中,文件被浏览器打开;不过,我想要下载文件。这里是我的代码:用C#下载PDF文件

控制器

 string name = id; //id is the name of the file 
     string contentType = "application/pdf"; 

     var files = objData.GetFiles(); //list of files 


     string filename = (from f in files 
          orderby f.DateEncrypted descending 
          where f.FileName == name 
          select f.FilePath).First(); //gets the location of the file 

     string FullName = (from f in files 
          where f.FileName == name 
          select f.FileName).First(); //gets the new id in new location to save the file with that name 



     //Parameters to File are 
     //1. The File Path on the File Server 
     //2. The content type MIME type 
     //3. The parameter for the file save by the browser 
     return File(filename, contentType, FullName); 

这里是我如何下拉菜单中使用它。

查看

<li><a id="copyURL" href="@Url.Action("Download", "Home", new { id = item.FileName})">Download</a></li> 

通过点击 “下载”,该文件被打开的浏览器。

回答

0

将您的内容类型设置为“application/octet-stream”,以便PDF插件不会尝试将其拾取并显示出来。然后浏览器会将其作为文件下载进行处理。

+0

浏览器仍然尝试打开它。我用Chrome和IE试了一下。 – user3853986 2014-09-30 22:24:27

+0

你可以尝试在你的return语句之前添加这行吗? 'Response.AddHeader(“content-disposition”,“attachment; filename =”+ filename);' – 2014-09-30 22:45:51

+0

仍然一样。我试过 Response.AddHeader(“content-disposition”,“attachment; filename =”+ filename); 和 Response.AddHeader(“content-disposition”,“attachment; filename =”+ FullName); – user3853986 2014-09-30 23:01:43

0

从网上下载文件:

这个例子说明了如何从网站到本地硬盘下载文件。如何下载文件的简单方法是使用WebClient类及其方法DownloadFile。此方法有两个参数,第一个是要下载的文件的URL,第二个参数是要保存文件的本地磁盘的路径。 同步下载文件

以下代码显示如何同步下载文件。此方法阻止主线程直到文件被下载或发生错误(在这种情况下抛出WebException)。 [C#]:

using System.Net; 

WebClient webClient = new WebClient(); 
webClient.DownloadFile("pdf file address", @"c:\myfile.pdf"); 

下载文件异步: 下载文件,而不会阻塞主线程使用异步方法DownloadFileAsync。您还可以设置事件处理程序来显示进度并检测文件是否已下载。 [C#]:

private void btnDownload_Click(object sender, EventArgs e) 
{ 
    WebClient webClient = new WebClient(); 
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); 
    webClient.DownloadFileAsync(new Uri("pdf file address"), @"c:\myfile.pdf"); 
} 

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
{ 
    progressBar.Value = e.ProgressPercentage; 
} 

private void Completed(object sender, AsyncCompletedEventArgs e) 
{ 
    MessageBox.Show("Download completed!"); 
} 

裁判:http://www.csharp-examples.net/download-files/

0

浏览器将尝试显示该文件,除非你指定不。

尝试在返回文件之前添加ContentDisposition。

var cd = new System.Net.Mime.ContentDisposition 
    { 
     FileName = filename, 
     Inline = false, 
    }; 
Response.AppendHeader("Content-Disposition", cd.ToString()); 
return File(filename, contentType, FullName);