コード例 #1
0
        public async Task <IActionResult> UpImage([FromForm] UploadModel model)
        {
            if (!ModelState.IsValid)
            {
                ApiData.code = 1005;
                ApiData.msg  = ModelState.GetErrMsg();
                return(Ok(ApiData));
            }
            if (Request.Form.Files == null || Request.Form.Files.Count == 0 || !Request.Form.Files[0].IsImage())
            {
                ApiData.code = 1006;
                ApiData.msg  = "请上传图片文件";
                return(Ok(ApiData));
            }
            var bucket = _bucketService.GetBucketBayName(model.bucket);

            if (bucket == null)
            {
                ApiData.code = 2001;
                ApiData.msg  = "bucket错误";
                return(Ok(ApiData));
            }

            IFormFile file = Request.Form.Files[0];
            string    sha1 = file.GetSHA1();
            var       item = _bucketImageService.GetSHA1(sha1);

            if (item != null)
            {
                ApiData.code = 0;
                ApiData.msg  = "上传成功";
                ApiData.data = new { url = $"/oss/imagecn{item.visiturl}" };
                return(Ok(ApiData));
            }

            if (!ValidSignature(model.signature, file.GetMD5(), model.VERB))
            {
                ApiData.code = 1005;
                ApiData.msg  = "签名验证失败";
                return(Ok(ApiData));
            }

            uint   crc32 = Crc32Algorithm.Compute(EncryptorHelper.GetMD5Byte(Guid.NewGuid().ToString()));
            var    dir   = Math.Abs(crc32) % 256;//256个子目录
            string f_dir = Math.Abs(crc32).ToString();


            string path = System.IO.Path.Combine(MediaItemConfig.RootDir, bucket.name, dir.ToString(), f_dir);
            //保存文件并且获取文件的相对存储路径
            var image = file.CreateImagePathFromStream(_mediaItemStorage, path);


            string visiturl = $"/oss/imagecn/{bucket.name}/{dir}/{f_dir}/{image.NewFileName}";

            _bucketImageService.AddImage(new Entities.bucket_image()
            {
                id            = CombGuid.NewGuidAsString(),
                bucket_id     = bucket.id,
                creation_time = DateTime.Now,
                ext_name      = image.ExtName,
                sha1          = sha1,
                visiturl      = visiturl,
                io_path       = image.IOPath,
                width         = image.Width,
                height        = image.Height,
                length        = file.Length
            });

            ApiData.code = 0;
            ApiData.msg  = "上传成功";
            ApiData.data = new { url = visiturl };
            await Task.FromResult(0);

            return(Ok(ApiData));
        }