【问题标题】:How to upload image on amzon s3 using .net web api c#?如何使用 .net web api c# 在 amazon s3 上上传图像?
【发布时间】:2018-01-06 16:23:15
【问题描述】:

我已经为图片上传创建了一个 api。在这段代码中,我在本地文件夹和存储中下载了上传时间图像。但我现在需要更改我的代码并将此图像下载移动到 amzon s3 上。我在搜索时间找到了一个链接,但在这个链接中,静态图片是上传,我需要从文件上传控件浏览图片并在 amzon 服务器上下载。但我不知道该怎么做。请任何人如何做到这一点,然后请帮助我。下面列出了我的代码。并补充说我在下面尝试了这个代码。

这是我上传图片的api方法:

[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload(string FileUploadType)
{            
try
{             
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
            string extension = Path.GetExtension(postedFile.FileName);
            Image img = null;
            string newFileName = "";

                newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
                string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
                string filePath = Path.Combine(path, newFileName);
                 SaveJpg(img, filePath);                                               
            return Request.CreateResponse(HttpStatusCode.OK, "Ok");
        }
    }                
}
catch (Exception ex)
{
    return ex;
}            
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}

这是我的保存图片 api =>

public static void SaveJpg(Image image, string file_name, long compression = 60)
    {
        try
        {
            EncoderParameters encoder_params = new EncoderParameters(1);

            encoder_params.Param[0] = new EncoderParameter(
                System.Drawing.Imaging.Encoder.Quality, compression);

            ImageCodecInfo image_codec_info =
                GetEncoderInfo("image/jpeg");

            image.Save(file_name, image_codec_info, encoder_params);
        }
        catch (Exception ex)
        {                
        }
    }

我已经尝试在服务器上上传静态图片的代码 =>

private string bucketName = "Xyz";
    private string keyName = "abc.jpeg";
    private string filePath = "C:\\Users\\I BALL\\Desktop\\image\\abc.jpeg";. // this image is store on server 
    public void UploadFile()
    {
        var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

        try
        {
            PutObjectRequest putRequest = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = keyName,
                FilePath = filePath,
                ContentType = "text/plain"
            };

            PutObjectResponse response = client.PutObject(putRequest);
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                ||
                amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                throw new Exception("Check the provided AWS Credentials.");
            }
            else
            {
                throw new Exception("Error occurred: " + amazonS3Exception.Message);
            }
        }
    }

在这里我展示了我的代码,但我需要与我的代码保持一致,所以如何做到这一点,请任何知道如何做到这一点的人。

【问题讨论】:

标签: c# image asp.net-web-api amazon-s3


【解决方案1】:

这可能为时已晚,但我是这样做的:

简短回答:适用于 .Net 的 Amazon S3 开发工具包有一个名为“TransferUtility”的类,它接受一个 Stream 对象,因此只要您可以将文件转换为从抽象 Stream 类派生的任何类,您就可以上传文件。

长答案: httprequest 发布的文件有一个 inputStream 属性,所以在你的 foreach 循环中:

var postedFile = httpRequest.Files[file];

如果你扩展这个对象,它的类型是“HttpPostedFile”,所以你可以通过 InputStream 属性访问 Stream:

这是来自工作示例的一些 sn-ps:

//get values from the headers
HttpPostedFile postedFile = httpRequest.Files["File"]; 
//convert the posted file stream a to memory stream 
System.IO.MemoryStream target = new System.IO.MemoryStream();
postedFile.InputStream.CopyTo(target);
//the following static function is a function I built which accepts the amazon file key and also the object that will be uploaded to S3, in this case, a MemoryStream object
s3.WritingAnObject(fileKey, target);

S3 是一个名为“S3Uploader”的类的实例,这里有一些可以帮助你前进的 sn-ps, 以下是一些需要的命名空间:

using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;

类构造函数:

    static IAmazonS3 client;
    static TransferUtility fileTransferUtility;

    public S3Uploader(string accessKeyId, string secretAccessKey,string bucketName)
    {
        _bucketName = bucketName;

        var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);
        client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);
        fileTransferUtility = new TransferUtility(client);
    }

请注意,我们正在使用 BasicAWSCredentials 类创建凭证,而不是直接将其传递给 AmazonS3Client。然后我们使用 fileTransferUtility 类来更好地控制发送到 S3 的内容。以下是基于 Memory Stream 的上传工作方式:

 public void WritingAnObject(string keyName, MemoryStream fileToUpload)
    {
        try
        {
            TransferUtilityUploadRequest fileTransferUtilityRequest = new 
            TransferUtilityUploadRequest
            {
                StorageClass = S3StorageClass.ReducedRedundancy,
                CannedACL = S3CannedACL.Private
            };
            fileTransferUtility.Upload(fileToUpload, _bucketName, keyName);
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            //your error handling here
        }
    }

希望这对有类似问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多