我正在从Amazon S3检索文件.我想将文件转换为字节,以便我可以按如下方式下载:
var download = new FileContentResult(bytes, "application/pdf"); download.FileDownloadName = filename; return download;
我有这里的文件:
var client = Amazon.AWSClientFactory.CreateAmazonS3Client( accessKey, secretKey, config ); GetObjectRequest request = new GetObjectRequest(); GetObjectResponse response = client.GetObject(request);
我知道response.WriteResponseStreamToFile()但我想将文件下载到常规下载文件夹.如果我将GetObjectResponse转换为字节,我可以返回该文件.我怎样才能做到这一点?
这是我为其他需要它的人找到的解决方案:
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(); } }
另一种选择:
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); } }