How can I get GetObjectResponse bytes from S3?

I am extracting a file from Amazon S3. I want to convert a file to bytes in order to download it as follows:

var download = new FileContentResult(bytes, "application/pdf"); download.FileDownloadName = filename; return download; 

I have a file here:

 var client = Amazon.AWSClientFactory.CreateAmazonS3Client( accessKey, secretKey, config ); GetObjectRequest request = new GetObjectRequest(); GetObjectResponse response = client.GetObject(request); 

I know about response.WriteResponseStreamToFile (), but I want to upload the file to the regular downloads folder. If I convert GetObjectResponse to bytes, I can return the file. How can i do this?

+5
source share
2 answers

Here is the solution I found for everyone who needs it:

 GetObjectResponse response = client.GetObject(request); using (Stream responseStream = response.ResponseStream) { var bytes = ReadStream(responseStream); var download = new FileContentResult(bytes, "application/pdf"); download.FileDownloadName = filename; return download; } 

 public static byte[] ReadStream(Stream responseStream) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } 
+7
source

Another option:

 Stream rs; using (IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client()) { GetObjectRequest getObjectRequest = new GetObjectRequest(); getObjectRequest.BucketName = "mybucketname"; getObjectRequest.Key = "mykey"; using (var getObjectResponse = client.GetObject(getObjectRequest)) { getObjectResponse.ResponseStream.CopyTo(rs); } } 
+5
source

Source: https://habr.com/ru/post/1237608/


All Articles