从asp.net中的文件夹下载文件

时间:2014-03-14 11:43:17

标签: c# asp.net

我正在开发一个网站,我上传文件并存储在文件夹中。上传文档工作正常,但下载代码不起作用。我需要从文件夹下载文件。

protected void btnDownload_Click(object sender, EventArgs e)
{        
         lblresume.Text = "~/Student_Resume/" + fuResume.FileName.ToString();         
         if (lblresume.Text != string.Empty)        
         {
             string filePath = lblresume.Text;             
             Response.ContentType = "doc/docx";             
             Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");              
             Response.TransmitFile(Server.MapPath(filePath));             
             Response.End();         
         }    
}

3 个答案:

答案 0 :(得分:7)

试试这个

protected void btnDownload_Click(object sender, EventArgs e)
{        
     lblresume.Text = "~/Student_Resume/" + fuResume.FileName.ToString();         
     if (lblresume.Text != string.Empty)        
     {
         WebClient req = new WebClient();
         HttpResponse response = HttpContext.Current.Response;
         string filePath = lblresume.Text;               
         response.Clear();
         response.ClearContent();
         response.ClearHeaders();
         response.Buffer = true;
         response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension");
         byte[] data = req.DownloadData(Server.MapPath(filePath));
         response.BinaryWrite(data);
         response.End();                   
     }    
}

答案 1 :(得分:0)

中的

Filepath

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\""); 

应该是物理路径;而不是从~开始 内容类型应为"application/ms-word"

答案 2 :(得分:0)

protected void btnDownload_Click(object sender, EventArgs e)
{        
     lblresume.Text = "~/Student_Resume/" + fuResume.FileName.ToString();         
     if (lblresume.Text != string.Empty)        
     {
         string filePath = lblresume.Text;             
         Response.ContentType = "doc/docx";             
         Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fuResume.FileName.ToString() + "\"");              
         Response.TransmitFile(Server.MapPath(filePath));             
         Response.End();         
     }    
}

试试这段代码。这应该有用。

相关问题