.net webapi 接收上传图片
protected async Taskpaths,T value)>> UploadFile () { ResponseResult<(Dictionary paths, T entity)> response = new ResponseResult<(Dictionary paths, T entity)>(); Dictionary filePaths = new Dictionary (); 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 (value); } else { t = ChangeTo (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 (string str) { T result = default(T); result = (T)Convert.ChangeType(str, typeof(T)); return result; }
使用
[HttpPost] [AllowAnonymous] public async Task> UploadTest() { ResponseResult