WebApi上傳圖片
阿新 • • 發佈:2019-01-11
/// <summary> /// 上傳圖片 /// </summary> /// <returns>成功返回圖片URL,失敗則返回錯誤資訊</returns> [HttpPost] public BaseResponse<string> Upload() { try { var content = Request.Content; var tempUploadFiles = "/Upload/TempUploadFiles/"; var newFileName = ""; string filePath = ""; string extname = ""; string returnurl = ""; var sp = new MultipartMemoryStreamProvider(); Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait(); foreach (var item in sp.Contents) { if (item.Headers.ContentDisposition.FileName != null) { var filename = item.Headers.ContentDisposition.FileName.Replace("\"", ""); FileInfo file = new FileInfo(filename); string fileTypes = "gif,jpg,jpeg,png,bmp"; if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1) { throw new ApplicationException("不支援上傳檔案型別"); } //if (file.Length> 5242880) //{ // throw new UserFriendlyException(L("檔案過大")); //} extname = filename.Substring(filename.LastIndexOf('.'), (filename.Length - filename.LastIndexOf('.'))); newFileName = Guid.NewGuid().ToString().Substring(0, 6) + extname; string newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/"; if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath)) { Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath); } filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName); returnurl = Path.Combine(tempUploadFiles + newFilePath, newFileName); var ms = item.ReadAsStreamAsync().Result; using (var br = new BinaryReader(ms)) { if (ms.Length > 1048576 * 5) { //throw new UserFriendlyException(L("檔案過大")); } var data = br.ReadBytes((int)ms.Length); File.WriteAllBytes(filePath, data); } } } // return returnurl; return new BaseResponse<string> { Success = true, Data = returnurl }; } catch (Exception ex) { return new BaseResponse<string> { Success = false, Data = ex.Message, Code = 1 }; } }
在web.config檔案的<system.webserver></system.webserver>節點下新增跨域設定
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Max-Age" value="30"/> <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/> <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" /> </customHeaders> </httpProtocol>