• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

.net webapi 接收上传图片

开发技术 开发技术 4小时前 2次浏览
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;
            }
        }

  


程序员灯塔
转载请注明原文链接:.net webapi 接收上传图片
喜欢 (0)