public async Task <IActionResult> EditAdminUser(AdminUserFormModel model, IFormFile headImg)
        {
            string headImgUrl = string.Empty;

            if (headImg?.Length > 1024 * 1024)
            {
                return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "上传的图片不能超过1MB", null)));
            }
            else if (headImg?.Length > 0)
            {
                //判断文件格式
                string[] extArr  = { ".jpg", ".png", ".gif", ".jpeg" };
                string   fileExt = Path.GetExtension(headImg.FileName);
                if (!extArr.Contains(fileExt))
                {
                    return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "选择的图片中包含不支持的格式", null)));
                }

                //计算文件的MD5值并拼接文件路径
                string   fileMd5  = GetMd5Hash(headImg.OpenReadStream());
                string   fileName = $"{fileMd5}{fileExt}";
                DateTime now      = DateTime.Now;
                string   fullPath = $"/uploadFile/{now.Year}/{now.Month}/{now.Day}/{fileName}";

                //文件上传至又拍云中
                UpYun upYun = new UpYun
                {
                    Operator = "rentalsite",
                    Password = "******"
                };

                byte[] fileByteArr = StreamToBytes(headImg.OpenReadStream());  //Stream转换byte[]
                bool   isOK        = await upYun.WriteFileAsync(fileByteArr, fullPath);

                if (!isOK)
                {
                    return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "文件上传失败", null)));
                }

                headImgUrl = $"https://aspnetweb.b0.upaiyun.com{fullPath}";
            }

            model.HeadImgUrl = headImgUrl;
            string json = await PutAsync(model, _urlSettings.AdminUser.EditAdminUser);

            Response.StatusCode = JsonConvert.DeserializeObject <ResultModel>(json).Status;
            return(Content(json, "application/json", Encoding.UTF8));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="ext">文件扩展名</param>
        /// <returns>是否上传成功;文件路径</returns>
        public static async Task <(bool, string)> FileUpload(byte[] buffer, string ext)
        {
            UpYun upYun = new UpYun
            {
                Operator = "rentalsite",
                Password = "******"
            };
            //计算文件的MD5值并拼接文件路径
            string   fileMd5  = GetMd5Hash(buffer);
            string   fileName = $"{fileMd5}{ext}";
            DateTime now      = DateTime.Now;
            string   fullPath = $"/uploadFile/{now.Year}/{now.Month}/{now.Day}/{fileName}";

            //文件上传至又拍云中
            bool isOK = await upYun.WriteFileAsync(buffer, fullPath);

            return(isOK, fullPath);
        }