当我在生产中上传图像时不起作用

时间:2019-05-16 16:13:17

标签: amazon-s3 aws-sdk bucket

当我使用此代码将文件(图像)上传到我的S3存储桶时,使用localhost可以完美运行;但是,当我以某种方式发布代码时,它破坏了文件并且仅显示黑屏。我是否需要在存储桶或代码中发送或更改某些内容?

public static async Task<UploadPhotoModel> UploadPhoto(IFormFile file,string bucket)
  {
    // connecting to the client
    var client = new AmazonS3Client(accessKey, accessSecret, Amazon.RegionEndpoint.CACentral1);

    // get the file and convert it to the byte[]
    byte[] fileBytes = new Byte[file.Length];
    file.OpenReadStream().Read(fileBytes, 0, int.Parse(file.Length.ToString()));


     var fileName = Guid.NewGuid().ToString() + file.FileName;
     PutObjectResponse response = null;
            using (var stream = new MemoryStream(fileBytes))
            {

                var request = new PutObjectRequest
                {
                    BucketName = bucket,
                    Key = fileName,
                    InputStream = stream,
                    ContentType = file.ContentType,
                    CannedACL = S3CannedACL.PublicRead,               
                };
                try
                {
                    response = await client.PutObjectAsync(request);
                }
                catch (Exception  ec)
                {

                    Debug.Write(ec);
                }
            };

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return new UploadPhotoModel
                {
                    Success = true,
                    FileName = fileName,
                    FileURL = "https://s3.ca-central-1.amazonaws.com/" + bucket + '/' + fileName,                 
                };
            }
            else
            {
                // this model is up to you, in my case I have to use it following;
                return new UploadPhotoModel
                {
                    Success = false
                };
            }
        }

0 个答案:

没有答案