2012-10-11 60 views
5

我一直在搜索互聯網,但找不到任何有用的答案。保存對話框下載文件,將文件從ASP.NET服務器保存到客戶端

我有一個ASP.NET網站,它部署在服務器上。 服務器上的ASP.NET網站可以訪問名爲W:/的目錄。 公司的客戶可以訪問該網站。該網站在列表框中列出來自W:/目錄的所有PDF文件。客戶端應該能夠從列表框中選擇PDF文件並通過選擇它的位置將它們保存到其本地PC中。

就像保存爲網頁上的文件一樣。

您能否提供一些解決方案或解決?

回答

0

正確的關鍵字是「文件瀏覽器asp.net」,以找到很多與源代碼的例子。

這是一個從CodeProject:在字節從W驅動器將

http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser

+0

謝謝@Aristos! – user1734609

+0

@ user1734609這是你在找什麼? :) – Aristos

+0

我已閱讀完文章,但不完全:)我有一個列表框中的PDF文件名。 W:/目錄中的文件位於不同的服務器上,但位於域內。列表框列出了該目錄的所有文件名。公司內部的客戶端打開網站時可以從目錄獲取PDF文件的列表。然後選擇一個或多個並點擊另存爲。而且應該可以保存在自己的PC上:)你明白這一點嗎? :) – user1734609

0

獲取文件的內容[],並將其寫入本地文件。

byte[] data = File.ReadAllBytes(WDriveFilePath) 

FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile)); 

file.Write(data, 0, data.Length); 
file.Close(); 
+0

這不提供保存對話框。 – bgmCoder

4

最後我找到了一篇文章,它會提示一個保存對話框從ASP.NET

我張貼在這裏下載一個文件,可以幫助別人,以及和節省一些時間。

String FileName = "FileName.txt"; 
String FilePath = "C:/...."; //Replace this 
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
response.ClearContent(); 
response.Clear(); 
response.ContentType = "text/plain"; 
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); 
response.TransmitFile(FilePath); 
response.Flush(); 
response.End(); 
+1

感謝Cory Mathews的文章。 – user1734609

+0

它可以用於下載.zip文件嗎?應該使用哪種ContentType? – alegz

-1

我已經做了這樣的事情來獲取文件。

protected void btnExportFile_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       Thread newThread = new Thread(new ThreadStart(ThreadMethod)); 
       newThread.SetApartmentState(ApartmentState.STA); 
       newThread.Start();  

       // try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception . 


      } 
      catch (Exception ex) 
      { 

      } 

     } 

     static void ThreadMethod() 
     { 
      Stream myStream; 
      SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 
      saveFileDialog1.FilterIndex = 2; 
      saveFileDialog1.RestoreDirectory = true; 

      if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
      { 
       if ((myStream = saveFileDialog1.OpenFile()) != null) 
       { 
        // Code to write the stream goes here. 
        myStream.Close(); 
       } 
      } 
     } 
1

這是對user1734609解決方案的擴展,它在本地獲取文件。

若要從服務器下載文件到客戶端:

public void DownloadFile() 
     { 
      String FileName = "201604112318571964-sample2.txt"; 
      String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName; 
      System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
      response.ClearContent(); 
      response.Clear(); 
      response.ContentType = "text/plain"; 
      response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); 
      response.TransmitFile(FilePath); 
      response.Flush(); 
      response.End(); 


     } 
相關問題