0

I have create one api for the image upload. in this code i have upload time image download in my local folder and store. but i need now change my code and move this image download on amzon s3. i have found one link in searching time but in this link static image is upload i need image browse from the file upload control and download on amzon server. but how can do that i have no idea. please any one how can do that then please help me. here below listed my code. and also add i have try this code in below.

this is my api method for the image upload :

[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");
}

This is my save image 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)
        {                
        }
    }

i have try this code with static image upload on server =>

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);
            }
        }
    }

here i have show my code but i need to marge with my code so how can do that please any one know how can do that.

2

1 Answer 1

1

This might be too late, but here is how I did it:

Short Answer: Amazon S3 SDK for .Net has a class called "TransferUtility" which accepts a Stream object, so as long as you can convert your file to any Class derived from the abstract Stream class, you can upload the file.

Long Answer: The httprequest posted files has an inputStream property, so inside your foreach loop:

var postedFile = httpRequest.Files[file];

If you expand on this object, it is of type "HttpPostedFile", so you have access to the Stream through the InputStream property:

Here is some snippets from a working sample:

//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);

The S3 is an instance of a class called "S3Uploader", here are some snippets that can get you going, below are some needed namespaces:

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

class constructor:

    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);
    }

Notice here that we are creating the credentials using the BasicAWSCredentials class instead of passing it to the AmazonS3Client directly. And then we are using fileTransferUtility class to have better control over what is sent to S3. and here is how the Upload works based on 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
        }
    }

Hope this helps someone with similar issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.