1 [HttpPost] 2 public Task<Hashtable> ImgUpload() 3 { 4 // 檢查是否是 multipart/form-data 5 if (!Request.Content.IsMimeMultipartContent("form-data")) 6 throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 7 //文件保存目錄路徑 8 string SaveTempPath = "~/SayPlaces/" + "/SayPic/SayPicTemp/"; 9 String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath); 10 // 設置上傳目錄 11 var provider = new MultipartFormDataStreamProvider(dirTempPath); 12 //var queryp = Request.GetQueryNameValuePairs();//獲得查詢字符串的鍵值集合 13 var task = Request.Content.ReadAsMultipartAsync(provider). 14 ContinueWith<Hashtable>(o => 15 { 16 Hashtable hash = new Hashtable(); 17 hash["error"] = 1; 18 hash["errmsg"] = "上傳出錯"; 19 var file = provider.FileData[0];//provider.FormData 20 string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); 21 FileInfo fileinfo = new FileInfo(file.LocalFileName); 22 //最大文件大小 23 int maxSize = 10000000; 24 if (fileinfo.Length <= 0) 25 { 26 hash["error"] = 1; 27 hash["errmsg"] = "請選擇上傳文件。"; 28 } 29 else if (fileinfo.Length > maxSize) 30 { 31 hash["error"] = 1; 32 hash["errmsg"] = "上傳文件大小超過限制。"; 33 } 34 else 35 { 36 string fileExt = orfilename.Substring(orfilename.LastIndexOf('.')); 37 //定義允許上傳的文件擴展名 38 String fileTypes = "gif,jpg,jpeg,png,bmp"; 39 if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) 40 { 41 hash["error"] = 1; 42 hash["errmsg"] = "上傳文件擴展名是不允許的擴展名。"; 43 } 44 else 45 { 46 String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo); 47 String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo); 48 fileinfo.CopyTo(Path.Combine(dirTempPath, newFileName + fileExt), true); 49 fileinfo.Delete(); 50 hash["error"] = 0; 51 hash["errmsg"] = "上傳成功"; 52 } 53 } 54 return hash; 55 }); 56 return task; 57 }