Skip to content

Instantly share code, notes, and snippets.

@BaileyMillerSSI
Created October 20, 2018 09:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BaileyMillerSSI/3a60d57e28ada9794234a622a57a6974 to your computer and use it in GitHub Desktop.
Save BaileyMillerSSI/3a60d57e28ada9794234a622a57a6974 to your computer and use it in GitHub Desktop.
[HttpGet("{bucketName}/{fileName}")]
public async Task<IActionResult> DownloadFileAsync([FromRoute]string bucketName, [FromRoute]string fileName)
{
var objectRequest = await _service.DownloadFileAsync(bucketName, fileName);
if (objectRequest.Status == System.Net.HttpStatusCode.OK)
{
Response.Headers.Add("Content-Length", objectRequest.Content_Length.ToString());
return new FileStreamResult(objectRequest.FileStream, "application/octet-stream")
{
LastModified = objectRequest.LastModified,
FileDownloadName = objectRequest.FileName
};
}
else
{
return BadRequest(objectRequest.Message);
}
}
public class S3StreamResponse : S3Response
{
public Stream FileStream { get; set; }
public String FileName { get; set; }
public String Content_Type { get; set; }
public long Content_Length { get; set; }
public DateTime LastModified { get; set; }
}
public async Task<S3StreamResponse> DownloadFileAsync(string bucketName, string fileName)
{
try {
var getRequest = new GetObjectRequest()
{
BucketName =bucketName,
Key = fileName
};
var response = await _client.GetObjectAsync(getRequest);
return new S3StreamResponse()
{
Status = System.Net.HttpStatusCode.OK,
Content_Length = response.ContentLength,
FileStream = response.ResponseStream,
LastModified = response.LastModified,
FileName = response.Key,
Message = "Successfully returned stream body"
};
}
catch (AmazonS3Exception e)
{
Debug.WriteLine(e.Message);
return new S3StreamResponse()
{
Status = System.Net.HttpStatusCode.BadRequest,
Message = e.Message.Replace("key", "file")
};
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
return new S3StreamResponse()
{
Status = System.Net.HttpStatusCode.BadRequest,
Message = e.Message
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment