2014-10-30 68 views
1

我在ListView中有一個ImageButton控件,單擊它時應該使用正確的ID下載圖像。Response.AddHeader將文件路徑看作文件名

這裏的ImageButton的ASPX:

<asp:ImageButton runat="server" ID="ibtDownloadImage" ImageUrl="img/downloadIcon.png" OnClick="ibtDownloadImage_OnClick" CommandArgument='<%# Convert.ToString(Eval("ID"))+Convert.ToString(Eval("FileExtension")) %>' /> 

正如你所看到的,被點擊時,它執行了「ibtDownloadImage_OnClick」的方法,並設置命令參數的ID加FileExtension(例如,1。 jpg,這是圖像的名稱)。

爲ibtDownloadImageOnClick我的C#代碼是:

protected void ibtDownloadImage_OnClick(object sender, EventArgs e) 
     { 


      ImageButton img = (ImageButton)sender; 
      string file = img.CommandArgument; 

      String imgURLtoDownload = @"img/uploads/"+file; 


      Response.AddHeader("Content-Disposition", "attachment; filename=" + imgURLtoDownload); 
     } 

當我點擊ImageButton控件,就會下載一個名爲 「IMG-上傳-1.JPG」(不講話引號)的文件,因此它似乎要採取我想成爲文件路徑作爲名稱的一部分,並將/替換爲...

有關如何解決此問題的任何想法?這似乎應該是一個簡單的解決方案。

我已經在Response.AddHeader線斷點和imgURLtoDownload的內容運行調試IMG /上傳/ 1.JPG(因爲它應該是)..

+0

'Response.ContentType ='其中是這部分的代碼被分配..也是此行正確'字符串imgURLtoDownload = @ 「IMG /上傳/」 +文件;'它應該被指向'的ImageUrl =「img/downloadIcon.png」'也試着在img之前添加一個'〜',如果你還有問題 – MethodMan 2014-10-30 16:07:32

回答

0

可以讀取文件內容爲二進制,讓說你有這個功能,這需要文件名字節數組作爲二進制內容,並且該函數名稱GetFileContent(Filepath)。然後,您可以使用該功能將內容寫入回覆並指定自定義路徑。

ImageButton img = (ImageButton)sender; 
string file = img.CommandArgument; 
String imgURLtoDownload = @"img/uploads/"+file; 
byte[] data= GetFileContent(Server.MapPath(imgURLtoDownload)); 
Response.Clear(); 
Response.AddHeader("Content-Disposition", "attachment; filename=" + file); 
Response.ContentType = System.Web.MimeMapping.GetMimeMapping(Server.MapPath(imgURLtoDownload));  
Response.BinaryWrite(data); 
Response.End(); 


public byte[] GetFileContent(string Filepath) 
{ 
    return System.IO.File.ReadAllBytes(Filepath); 
} 
+0

有了這段代碼,我得到錯誤:「找不到路徑的一部分'C:\ Program Files (x86)\ IIS Express \ img \ uploads \ 1.jpg'。「當我點擊按鈕。似乎無法進入父目錄 – Frayt 2014-10-30 16:17:49

+1

Nevermind,沒有看到你添加了Server.MapPath!這完全解決了,非常感謝! – Frayt 2014-10-30 16:19:20

+0

還有一件事:下載的文件可以是.jpg,.png,.jpeg或.gif。我應該如何展開Response.ContentType? – Frayt 2014-10-30 16:25:50