如何將二進制數據流式傳輸到磁盤,用戶首先選擇位置路徑?如何使用c#在asp.net中將二進制數據流式傳輸到磁盤上#
我到目前爲止: 用戶單擊我的RadGrid,然後使用.ToArrar()獲取Binary(或byte [])。
我想要一些東西,在那裏用戶被要求瀏覽他的電腦在位置和打擊接受/取消。接受將啓動流寫入文件。
如何將二進制數據流式傳輸到磁盤,用戶首先選擇位置路徑?如何使用c#在asp.net中將二進制數據流式傳輸到磁盤上#
我到目前爲止: 用戶單擊我的RadGrid,然後使用.ToArrar()獲取Binary(或byte [])。
我想要一些東西,在那裏用戶被要求瀏覽他的電腦在位置和打擊接受/取消。接受將啓動流寫入文件。
基本上,您將響應對象設置爲oclet類型,推送數據並將其發送出去。客戶端瀏覽器確定它將如何向用戶顯示任何需要的對話框。
這是來自內部網絡應用程序的下載實用程序頁面。完整的代碼包括防止用戶嘗試讀取我爲此示例所忽略的路徑沙箱以外的文件。
string document = "... some server document file name ...";
string fullpath = Server.MapPath("your path"+document);
Response.ContentType = ExtentionToContentType(document);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", document));
byte[] data = System.IO.File.ReadAllBytes(fullpath);
Response.AppendHeader("Content-Length", data.Length.ToString());
Response.BinaryWrite(data);
Response.End();
public string ExtentionToContentType(string file)
{
switch (System.IO.Path.GetExtension(file).ToLower())
{
case ".xls": return "application/vnd.ms-excel";
case ".doc": case ".docx": return "application/msword";
case ".ppt": return "application/vnd.ms-powerpoint";
case ".mdb": return "application/x-msaccess";
case ".zip": return "application/zip";
case ".jpg": case ".jpeg": case ".jpe": return "image/jpeg";
case ".tiff": return "image/tiff";
case ".bmp": return "image/bmp";
case ".png": return "image/png";
case ".gif": return "image/gif";
case ".avi": return "video/x-msvideo";
case ".mpeg": return "video/mpeg";
case ".rtf": case ".rtx": return "text/richtext";
case ".txt": return "text/plain";
case ".pdf": return "application/pdf";
default: return "application/x-binary";
}
}
你不會(也不能)直接流數據到用戶的磁盤或交互用戶的瀏覽器之外。在Web應用程序中,您只需將內容作爲標準HTTP響應傳遞給用戶。用戶的瀏覽器將負責其餘的事情。
關於此here有一個非常好的問題/答案。
瞭解HTTP協議不處理「文件」。它處理請求和響應,每個請求和響應由標題和正文組成。因此,您的Web應用程序會做的是製作一個響應,用戶的瀏覽器可能會將其解釋爲應該保存爲文件的響應。頭文件將爲瀏覽器提供做出這種解釋所需的東西,並且正文將爲瀏覽器提供數據。通常它涉及這些步驟:
content-length
,content-type
和可能的content-disposition
之類的東西,作爲向瀏覽器建議將響應保存爲文件的一種方式。
Thx對於這兩個很好的答案。我從兩方面都學到了。我接受了這個,因爲我可以從中複製:) – radbyx