.net webapi 接收上傳圖片
阿新 • • 發佈:2021-10-14
protected async Task<ResponseResult<(Dictionary<string,string> paths,T value)>> UploadFile<T>() { ResponseResult<(Dictionary<string, string> paths, T entity)> response = new ResponseResult<(Dictionary<string, string> paths, T entity)>(); Dictionary<string, string> filePaths = new Dictionary<string, string>(); try { // 是否請求包含multipart/form-data。 if (!Request.Content.IsMimeMultipartContent()) { response.Code = WebErrorCode.Failure.GetHashCode(); response.Message = "格式錯誤,請使用multipart/form-data上傳"; return response; } string root = System.Web.Hosting.HostingEnvironment.MapPath("/UploadFiles/"); if (!Directory.Exists(FileSavePath)) { Directory.CreateDirectory(FileSavePath); } var provider = new MultipartFormDataStreamProvider(root); // 閱讀表格資料並返回一個非同步任務. await Request.Content.ReadAsMultipartAsync(provider); // 檔案 foreach (var file in provider.FileData) { string uploadFileName = file.Headers.ContentDisposition.Name.TrimStart('"').TrimEnd('"'); string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); FileInfo fileinfo = new FileInfo(file.LocalFileName); if (fileinfo.Length <= 0) { continue; } string fileExt = orfilename.Substring(orfilename.LastIndexOf('.')); // 檔案儲存到指定地址 fileinfo.CopyTo(Path.Combine(FileSavePath, fileinfo.Name + fileExt), true); // web路徑 string path = FileWebPath + fileinfo.Name + fileExt; if (!filePaths.ContainsKey(file.LocalFileName)) { filePaths.Add(uploadFileName, path); } fileinfo.Delete();//刪除原檔案 } // 表單資料 // 1、僅處理json字串反序列化以及指定型別轉換 // 2、僅對第一個key的第一個值進行處理 string[] keys = provider.FormData.AllKeys; string value = string.Empty; T t = default(T); if (keys.Length > 0) { string[] values = provider.FormData.GetValues(keys[0]); if(values.Length > 0) { value = values[0]; if (Type.GetTypeCode(typeof(T)) == TypeCode.Object) { t = JsonConvert.DeserializeObject<T>(value); } else { t = ChangeTo<T>(value); } } } response.Code = WebErrorCode.Success.GetHashCode(); response.Data = (filePaths, t); return response; } catch (Exception ex) { Logging.Logger.Error(ex); response.Code = WebErrorCode.SystemError.GetHashCode(); return response; } } private T ChangeTo<T>(string str) { T result = default(T); result = (T)Convert.ChangeType(str, typeof(T)); return result; }
使用
[HttpPost] [AllowAnonymous] public async Task<ResponseResult<object>> UploadTest() { ResponseResult<object> response = new ResponseResult<object>(); try { /* * 上傳格式: * { * "file1": file, // 檔案1 * "file2": file, // 檔案2 * …… * "name": json // 表單資料,json字串/字串 * } * * 表單資料需要解析為物件時,上傳“json字串” * 表單資料僅僅上傳ID,Code等唯一資料時,上傳“字串”資料 */ //var result = await UploadFile<UserInfo>(); //UserInfo user = result.Data.value ?? new UserInfo(); var result = await UploadFile<int>(); int test = result.Data.value; Dictionary<string, string> paths = result.Data.paths; response.Data = new { paths, test }; return response; } catch (Exception ex) { Logging.Logger.Error(ex); return response; } }
歲月無情催人老,請珍愛生命,遠離程式碼!!!