WebApi FormData+檔案長傳 非同步+同步實現
阿新 • • 發佈:2018-11-11
// POST api/values public async Task Post() { try { // 檢查該請求是否含有multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); }// 方法一 System.Web.HttpFileCollection file = System.Web.HttpContext.Current.Request.Files; if (file.Count > 0) { //檔名 string name = file[0].FileName; //儲存檔案 string path = HttpContext.Current.Server.MapPath("~/") + name; file[0].SaveAs(path); } Dictionary<string, string> dicFormData = new Dictionary<string, string>(); foreach (var key in System.Web.HttpContext.Current.Request.Form.AllKeys) {//接收FormData dicFormData.Add(key, System.Web.HttpContext.Current.Request.Form[key]); } // 方法二 Dictionary<string, string> dic = new Dictionary<string, string>(); string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要將檔案存入的伺服器物理位置 var provider = new MultipartFormDataStreamProvider(root); // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file1 in provider.FileData) {//接收檔案 Trace.WriteLine(file1.Headers.ContentDisposition.FileName);//獲取上傳檔案實際的檔名 Trace.WriteLine("Server file path: " + file1.LocalFileName);//獲取上傳檔案在服務上預設的檔名 } foreach (var key in provider.FormData.AllKeys) {//接收FormData dic.Add(key, provider.FormData[key]); } } catch (Exception ex) { throw ex; } }