TOP

[ASP.NET] 檔案下載時檔案名稱亂碼

原本使用的下載方式會造成 檔案下載時檔案名稱亂碼。
因此變更檔案下載的方式,並且將檔案名稱做UrlEncode。
Dim filePath As String = "c:/123檔案.txt"
Dim wc As WebClient = New WebClient()
Dim byteFile() As Byte = Nothing
byteFile = wc.DownloadData(filePath)
Response.AppendHeader("content-disposition", "attachment;filename=" + "123檔案名稱")
HttpContext.Current.Server.UrlEncode(docPhysicalName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteFile)
Response.End()

參考資料:
http://bob.logdown.com/posts/94996-aspnet-file-download

Response.WriteFile 檔案下載方式一
using System.IO;

string filePath = "C:/porn.jpg";
FileInfo file = new FileInfo(filePath);
Response.Clear()
Response.Buffer = false; 
Response.ContentType = "application/octet-stream"; // 指定檔案類型
Response.AddHeader("Content-Disposition","attachment;filename="+"porn.jpg"); // 設定檔名
// System.Web.HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8) 解決中文檔名亂碼
Response.AppendHeader("Content-Length", file.Length.ToString()); // 表頭加入檔案大小
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
## System.Net.WebClient.DownloadData 檔案下載方式二

using System.Net;

WebClient wc = new WebClient();
byte[] byteFile = null;
string path = "C:/porn.jpg"; // 設定路徑
byteFile = wc.DownloadData(path);
string fileName = System.IO.Path.GetFileName(path); // 取得檔案名稱
Response.AppendHeader("content-disposition", "attachment;filename=" + "porn.jpg"); //設定檔名
// HttpContext.Current.Server.UrlEncode(fileName) 解決中文檔名亂碼
Response.ContentType = "application/octet-stream";  // 指定檔案類型   
Response.BinaryWrite(byteFile); // 內容轉出作檔案下載
Response.End();

亂碼處理的參考資料:

0 意見:

張貼留言