WebAPI实现移动端上传头像接口

测试时可以直接使用PostMan模拟发送请求

        /// <summary>
        /// 手机端上传头像接口
        /// </summary>
        /// <param name="LoginToken"></param>
        /// <param name="Base64String"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> UploadAvatar()
        {
            // 检查是否是 multipart/form-data 
            if (!Request.Content.IsMimeMultipartContent("form-data"))
                return CreateResponse(false, "请选择要上传的文件!");

            // 设置上传目录 
            string root = System.Web.HttpContext.Current.Server.MapPath("/upload/avatars/");
            var provider = new ReNameMultipartFormDataStreamProvider(root);
            string LoginToken = System.Web.HttpContext.Current.Request.Params["LoginToken"];
            var token = new Guid(LoginToken);
            var loginInfo = this.MobileService.GetLoginInfo(token);
            if (loginInfo == null)
            {
                return CreateResponse(false, "登录授权失败!");
            }

            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.FileData[0];
            var fileInfo = new FileInfo(file.LocalFileName);
            var fileStream = fileInfo.OpenRead();
            var img = System.Drawing.Image.FromStream(fileStream);
            UploadAvatar upload = new UploadAvatar();
            var result = upload.MobileUploadImage(img);
            //删除中间文件
            //解除占用TODO
            //if (File.Exists(file.LocalFileName))
            //{
            //    File.Delete(file.LocalFileName);
            //}
            if (result.success)
            {
                var person = this.FoundationService.GetPersonInfoById(loginInfo.UserID);
                if (person != null)
                {
                    person.Photo = result.sourceUrl;//头像缩略图地址
                    this.FoundationService.UpdatePersonInfo(person);
                    result.sourceUrl = "http://192.168.3.66:8008" + result.sourceUrl;
                }
            }
            return CreateResponse(true, result);
        }
public Result MobileUploadImage(Image _file)
        {
            bool isThumbnail = true;
            try
            {
                string fileExt = "jpg"; //文件扩展名,不含“.”

                path = HttpContext.Current.Server.MapPath("/upload/avatars/");//上传头像路径
                string newFileName = GetRamCode() + "." + fileExt; //随机生成新的文件名
                string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
                string upLoadPath = "/upload/avatars/yt/" + newFileName;//上传原图目录相对路径
                string upLoadPathS = "/upload/avatars/slt/" + newFileName;//上传缩略图目录相对路径

                //是否存在存放缩略图和原图的文件夹 没有则创建
                string pathS = HttpContext.Current.Server.MapPath("/upload/avatars/slt/");
                string pathY = HttpContext.Current.Server.MapPath("/upload/avatars/yt/");
                if (!Directory.Exists(pathS))
                {
                    Directory.CreateDirectory(pathS);
                }
                if (!Directory.Exists(pathY))
                {
                    Directory.CreateDirectory(pathY);
                }

                string newFilePath = path + "yt\" + newFileName; //上传后原图的路径
                string newThumbnailPath = path + "slt\" + newFileName; //上传后的缩略图路径

                #region 检查上传的物理路径是否存在,不存在则创建
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                #endregion

                #region 保存文件
                _file.Save(newFilePath);
                #endregion

                #region 图片剪裁
                //如果是图片,检查是否需要生成缩略图,是则生成
                if (IsImage(fileExt) && isThumbnail && thumbnailwidth > 0 && thumbnailheight > 0)
                {
                    Thumbnail.MakeThumbnailImage(newFilePath, newThumbnailPath, thumbnailwidth, thumbnailheight, "Cut");
                }
                else
                {
                    newThumbnailPath = newFilePath; //不生成缩略图则返回原图
                }
                #endregion

                //处理完毕,返回JOSN格式的文件信息
                return new Result() { success = true, msg = "操作成功!", sourceUrl = upLoadPathS };
            }
            catch
            {
                return new Result() { success = false, msg = "上传过程中发生意外错误!" };
            }
        }

使用PostMan模拟测试时要注意的地方:

Body中请求类型选择 form-data  选择文件的参数key是 MultipartFile

下图中Headers中的不要勾选

原文地址:https://www.cnblogs.com/kennyliu/p/6020217.html