2012-03-26 67 views
2

我必須在我的網站上提供一個選項來上傳多個文件,然後允許用戶下載這些文件。 我已經完成了上傳多個文件的一部分,但我不太清楚我將如何下載部分。 我首先想到爲每個文件的標籤動態添加超鏈接(因爲我不確定用戶將上傳多少文件)。 但它然後在瀏覽器中打開文件,並沒有給出選項來保存或打開文件。 主要問題是用戶可以提交任何類型的文件,如ms doc或xls或文本文件等,因此內容類型不固定。下載文件的代碼

我不清楚我該怎麼做我的意思是動態添加鏈接按鈕或動態添加超鏈接。之後,我將如何下載文件?我不能做

Response.WriteFile(Server.MapPath(@"~/logo_large.gif")); 

內容類型不明確。 請幫我有關下載代碼的所有類型的文件

+0

上傳文件時需要保存內容類型和文件長度。這會使下載變得容易很多。 – WraithNath 2012-03-26 12:14:32

+0

[在ASP.NET2.0中提供動態文件下載](http:// stackoverflow。問題/ 468893 /提供 - 動態文件下載在ASP - NET2-0) – 2014-06-13 17:03:58

回答

6

下載的文件:

public void DownLoad(string FName) 
    { 
     string path = FName; 
     System.IO.FileInfo file = new System.IO.FileInfo(path); 
     if (file.Exists) 
     { 
      Response.Clear(); 
      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
      Response.AddHeader("Content-Length", file.Length.ToString()); 
      Response.ContentType = "application/octet-stream"; 
      Response.WriteFile(file.FullName); 
      Response.End(); 

     } 
     else 
     { 
      Response.Write("This file does not exist."); 
     } 

    } 

但這是Word文檔/ DOCX文件。在該行:Response.ContentType = "application/octet-stream";您必須定義文件的類型。

顯示超級鏈接動態地寫一個循環,並去了所有被用戶和writh下面的代碼上傳的文件:

 yourdivId += "<a href='" + file.FullName + "' >" + file.Name + "</a></br>"; 
+0

正是這是我的問題..內容類型不固定..我用超鏈接選項,但它總是在瀏覽器中打開文件 – user1181942 2012-03-26 11:08:52

+0

爲什麼不能使用switch子句根據文件的擴展名定義內容類型?併爲超鏈接,你可以發佈你的代碼? – 2012-03-26 11:48:42

+0

非常感謝你..這對我來說很有效..但是我只用單個文件試過了。我所做的是爲所有上傳的文件動態添加鏈接按鈕。然後點擊事件文件被下載。我將如何知道要下載哪個文件。我的意思是如何將這些參數傳遞給事件? – user1181942 2012-03-27 04:36:05

0

你可以這樣說:

try 
     { 
      string strURL=txtFileName.Text; 
      WebClient req=new WebClient(); 
      HttpResponse response = HttpContext.Current.Response; 
      response.Clear(); 
      response.ClearContent(); 
      response.ClearHeaders(); 
      response.Buffer= true; 
      response.AddHeader("Content-Disposition","attachment;filename=\"" + Server.MapPath(strURL) + "\""); 
      byte[] data=req.DownloadData(Server.MapPath(strURL)); 
      response.BinaryWrite(data); 
      response.End(); 
     } 
     catch(Exception ex) 
     { 
    } 
1

希望這將幫助ü。()

Response.Clear(); 
Response.ContentType = YourFile.ToString(); 
Response.AddHeader("Content-Disposition", "attachment;filename=" + YourFileName); 
Response.OutputStream.Write(YourFile, 0, YourFile.Length); 
Response.Flush(); 
Response.End(); 

I have tried this to download img,txtfile,zip file,doc it works fine.. 
but little problem user will face that in my case when i opened a word(doc) file its ask 
me to openwith..? when i select MsWord it opened it correctly. 

爲了顯示這些文件,你可以做一個網格視圖,以顯示與一個下載鏈接的所有文件...

1

其實你可以按照不同的方式。

  1. 在上傳過程中指導用戶,並讓他在開始上傳之前指定文件類型。所以用戶必須從選擇中選擇內容類型。您需要保存文件及其內容類型之間的關聯。

  2. 創建文件擴展名和MIME類型之間的映射(See here for example)。您需要獲取文件擴展名並保存該文件及其內容類型之間的關聯。

  3. 嘗試自動識別內容類型。有一個Windows API可讓您識別文件的MIME類型。和here is some code

之後,您可以使用st mnmn解決方案。