.net webapi 接收上传图片

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;
            }
        }

  

posted @ 2021-10-14 17:00  我要找到我的全世界  阅读(197)  评论(0编辑  收藏  举报