最近做項目遇到文件下載的問題,原本采用的是直接用一個href鏈接到需要下載的文件來處理這個問題,后來發現,如果文件是一個圖片,瀏覽器會自動打開圖片而不是下載,需要用戶右擊另存為才可以下載,很不友好,后來上網找了一個a標簽的download屬性,經測試,谷歌瀏覽器支持下載,但是IE並不支持這個屬性,懶得去做那些兼容的操作了,在后台寫了一個下載的方法,直接前台調用就OK
- asp.net的下載方法
/// <summary> ///字符流下載方法 /// </summary> /// <param name="fileName">下載文件生成的名稱</param> /// <param name="fPath">下載文件路徑</param> /// <returns></returns> public void DownloadFile(string fileName, string fPath) { string filePath = Server.MapPath(fPath);//路徑 //以字符流的形式下載文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載文件而不是打開 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
- asp.net MVC 的下載方法
/// <summary> /// 下載文件的方法 /// </summary> /// <param name="path">文件絕對路徑</param> /// <param name="fileName">客戶端接收的文件名</param> /// <returns></returns> public static HttpResponseMessage Download(string path, string fileName) { var stream = File.OpenRead(path); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); try { httpResponseMessage.Content = new StreamContent(stream); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); if (!string.IsNullOrEmpty(fileName)) { httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8), }; } return httpResponseMessage; } catch { stream.Dispose(); httpResponseMessage.Dispose(); throw; } }
- .net Core 的下載方法
/// <summary> /// 下載文件 /// </summary> /// <param name="path">文件絕對路徑</param> /// <returns></returns> public ActionResult<dynamic> DownloadFiles(string path) { return File(new FileInfo(path).OpenRead(), "application/vnd.android.package-archive", "自定義的文件名"); }