1. 程式人生 > >WebApi實現單個檔案的上傳下載

WebApi實現單個檔案的上傳下載

上傳和下載是很常用的功能了,只有當用到的時候才發現不會寫...,經過一番百度、篩選、整理修改後,實現了功能,下面簡單的記錄下實現方法。

一、上傳功能

1.前端程式碼

上傳檔案 <input type="file" id="file" />
<input type="button" id="upload" value="上傳檔案" />

<script>
    //上傳
    $("#upload").click(function () {
        var formData = new FormData();
        var file 
= document.getElementById("file").files[0]; formData.append("fileInfo", file); $.ajax({ url: "../api/File/UploadFile", type: "POST", data: formData, contentType: false,//必須false才會自動加上正確的Content-Type processData: false,//必須false才會避開jQuery對 formdata 的預設處理,XMLHttpRequest會對 formdata 進行正確的處理
success: function (data) { alert(data); }, error: function (data) { alert("上傳失敗!"); } }); }); </script>

2.後臺程式碼

 1         /// <summary>
 2         /// 上傳檔案
 3         /// </summary>
 4         [HttpPost]
5 public string UploadFile() 6 { 7 string result = string.Empty; 8 try 9 { 10 string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/"); 11 HttpRequest request = System.Web.HttpContext.Current.Request; 12 HttpFileCollection fileCollection = request.Files; 13 // 判斷是否有檔案 14 if (fileCollection.Count > 0) 15 { 16 // 獲取檔案 17 HttpPostedFile httpPostedFile = fileCollection[0]; 18 string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 副檔名 19 string fileName = Guid.NewGuid().ToString() + fileExtension;// 名稱 20 string filePath = uploadPath + httpPostedFile.FileName;// 上傳路徑 21 // 如果目錄不存在則要先建立 22 if (!Directory.Exists(uploadPath)) 23 { 24 Directory.CreateDirectory(uploadPath); 25 } 26 // 儲存新的檔案 27 while (File.Exists(filePath)) 28 { 29 fileName = Guid.NewGuid().ToString() + fileExtension; 30 filePath = uploadPath + fileName; 31 } 32 httpPostedFile.SaveAs(filePath); 33 result = "上傳成功"; 34 } 35 } 36 catch (Exception) 37 { 38 result = "上傳失敗"; 39 } 40 return result; 41 }

 

二、下載功能

1.前端程式碼

 1 <form action="../api/File/DownloadFile" method="get" id="form">
 2    下載檔案 <input type="text" id="name" name="fileName" value="222" />
 3 </form>
 4 <input type="button" id="download" value="下載檔案" />
 5 
 6 <script>
 7     //下載
 8     $("#download").click(function () {
 9         var form = $("#form");
10         form.submit();
11     });
12 </script>

2.後臺程式碼

 1         /// <summary>
 2         /// 下載檔案
 3         /// </summary>
 4         /// <param name="fileName"></param>
 5         [HttpGet]
 6         public void DownloadFile(string fileName)
 7         {
 8             string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
 9             if (File.Exists(filePath))
10             {
11                 HttpResponse response = HttpContext.Current.Response;
12                 response.Clear();
13                 response.ClearHeaders();
14                 response.ClearContent();
15                 response.Buffer = true;
16                 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
17                 response.Charset = "GB2312";
18                 response.ContentEncoding = Encoding.GetEncoding("GB2312");
19                 response.ContentType = MimeMapping.GetMimeMapping(fileName);
20                 response.WriteFile(filePath);
21                 response.Flush();
22                 response.Close();
23             }
24         }

三、遇到的問題

1.寫了個測試的html頁,如何讓程式執行時開啟這個頁面,在預設執行的HomeControler中新增重定向程式碼

HttpContext.Response.Redirect("Html/Index.html", true);

 2.跨域問題

當問題1中html頁和後端程式分開部署時,就會產生跨域問題

可在web.config中進行如下配置

1   <system.webServer>
2     <httpProtocol>
3       <customHeaders>
4         <add name="Access-Control-Allow-Origin" value="*"/>
5         <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type,Accept,Origin"/>
6         <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
7       </customHeaders>    
8     </httpProtocol>
9   </system.webServer>

詳情可閱讀:https://www.cnblogs.com/landeanfen/p/5177176.html

Demo下載:https://pan.baidu.com/s/1zV1-4WvrP3ZTWwTDFAmExQ