简体   繁体   中英

How to read a file via ASP.Net Web API to S3 via Memory Stream

I want to read file as memory stream and send it to s3 bucket. Below is a working snippet which has two part.

Part 1: Takes a file and upload it to a local directory

Part 2: Takes a text and upload it to s3 bucket.

But I want to upload the file to s3 bucket rather than the text .

Below is the code snippet:

[httppost]    
public async void Upload()
{
        // Part 1:

        // LOGIC TO UPLOAD FILE TO A LOCAL LOCATION 
        var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];  // some local path
        var provider = new MultipartFormDataStreamProvider(fileuploadPath);
        var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
        foreach (var header in Request.Content.Headers)
        {
            content.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }
        await content.ReadAsMultipartAsync(provider);

        // Part 2:

        // LOGIC TO WRITE DATA TO s3 Bucket via Amazon Kinesis
        byte[] dataAsBytes = Encoding.UTF8.GetBytes("My Test Data for s3 bucket");
        using (MemoryStream memoryStream = new MemoryStream(dataAsBytes))
        {
                Amazon.KinesisFirehose.Model.PutRecordRequest putRecord = new Amazon.KinesisFirehose.Model.PutRecordRequest();
                putRecord.DeliveryStreamName = myStreamName;
                Record record = new Record();
                record.Data = memoryStream; // I WANT TO PUT FILE CONTENT HERE
                putRecord.Record = record;
                await kinesisClient.PutRecordAsync(putRecord);
        }
}

In above code snippet, I want to send the file that is getting uploaded to s3 bucket.

Psuedo Code:

Current Code
byte[] dataAsBytes = Encoding.UTF8.GetBytes("My Test Data for s3 bucket");
What I want
byte[] dataAsByte = Data should be read from the file 

You could read all bytes and construct a memory stream:

string fileName = provider.FileData.First().LocalFileName; // assuming you have one file
byte[] fileData = File.ReadAllBytes(fileName);
using (MemoryStream memoryStream = new MemoryStream(fileData))
{

Note that the maximum size allowed in that field is 50kb so you might want to add validation for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM