ASP.NET 在下載檔案時對其重新命名的思路及實現方法_實用技巧

來源:互聯網
上載者:User
有些時候為了保證檔案再上傳時不會覆蓋掉之前上傳的檔案,同時由於上傳的目標目錄裡的檔案可能很多,這個時候一個一個查是不太好的事情,所以這裡可以自動產生GUID使檔案名稱重新命名成GUID_原來的名稱.副檔名。但是在下載的時候最好可能保證恢複到原來的名稱。這個時候聽傷神的。搜了一下相關資料後得知可使用response來解決。具體代碼如下。

[csharp] 
複製代碼 代碼如下:

<pre name="code" class="csharp">string path = Server.MapPath("aa\\ahaakladahsasdas_bb.zip"); 
            string newfileName = ""; 
            if (File.Exists(path)) 
            { 
                FileInfo fi = new FileInfo(path); 
                Response.Clear();//Clear 方法刪除緩衝區中的所有 HTML 輸出。但 Clear 方法只刪除響應本文 
                //而不刪除響應標題。可以用該方法處理錯誤情況。 
                Response.ClearHeaders(); 
                Response.Buffer = false;//這句話的意思就是指明輸出頁面是否被緩衝,當屬性值為True時, 
                //伺服器將不會向用戶端發送任何資訊,直到所有程式執行完或者遇到  
                //Response.Flush或Response.End語句,才會釋放緩衝區的資訊。 
                string filename = Path.GetFileName(path); 
                newfileName = newfileName + filename.Substring(filename.LastIndexOf(".")); 
                Response.Clear(); 
                Response.ClearHeaders(); 
                Response.Buffer = false; 

                newfileName = HttpUtility.UrlEncode(newfileName);// 這一步彈出下載儲存的對話方塊,出現檔案名稱亂碼,但變數中的檔案名稱是正常的。   
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + newfileName);//為使用者儲存檔案是顯示的名稱 
                //告訴用戶端這個響應內容的類型為attachment 你是通過Response.AppendHeader("content-type", "attachment"); 申明的。 

                Response.AppendHeader("Content-Length", fi.Length.ToString()); 
                Response.ContentType = "application/octet-stream"; 
                Response.WriteFile(newfileName);//用response來返迴文件的路徑   
                Response.Flush();//清空response   
                Response.End(); 
                //Response.End(); 如果拋異常的話可使用 
                //HttpContext.Current.ApplicationInstance.CompleteRequest(); 
            } 
            else 
            { 
                Response.Write("<script langauge=javascript>alert(‘檔案不存在!');</script>"); 
            }

</pre><br> 
<br> 
<pre></pre> 
<p></p> 
<pre></pre> 
<p></p> 
<pre></pre> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.