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.前端代碼
<form action="../api/File/DownloadFile" method="get" id="form"> 下載文件 <input type="text" id="name" name="fileName" value="222" /> </form> <input type="button" id="download" value="下載文件" /> <script> //下載 $("#download").click(function () { var form = $("#form"); form.submit(); }); </script>
2.后台代碼
1 /// <summary> 2 /// 下載文件 3 /// </summary> 4 [HttpGet] 5 public void DownloadFile() 6 { 7 var request = HttpContext.Current.Request; 8 NameValueCollection nvCollection = request.Params; 9 string fileName = nvCollection.GetValues("fileName")[0]; 10 string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName); 11 if (File.Exists(filePath)) 12 { 13 HttpResponse response = HttpContext.Current.Response; 14 response.Clear(); 15 response.ClearHeaders(); 16 response.ClearContent(); 17 response.Buffer = true; 18 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName)); 19 response.Charset = "GB2312"; 20 response.ContentEncoding = Encoding.GetEncoding("GB2312"); 21 response.ContentType = MimeMapping.GetMimeMapping(fileName); 22 response.WriteFile(filePath); 23 response.Flush(); 24 response.Close(); 25 } 26 }
