Created
July 26, 2016 22:27
-
-
Save mikeesouth/19f414366ab7d14e7ad5b093ef8f65f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Downloads a blob file. | |
/// </summary> | |
/// <param name="blobId">The ID of the blob.</param> | |
/// <returns></returns> | |
public async Task<HttpResponseMessage> GetBlobDownload(int blobId) | |
{ | |
// IMPORTANT: This must return HttpResponseMessage instead of IHttpActionResult | |
try | |
{ | |
var result = await _service.DownloadBlob(blobId); | |
if (result == null) | |
{ | |
return new HttpResponseMessage(HttpStatusCode.NotFound); | |
} | |
// Reset the stream position; otherwise, download will not work | |
result.BlobStream.Position = 0; | |
// Create response message with blob stream as its content | |
var message = new HttpResponseMessage(HttpStatusCode.OK) | |
{ | |
Content = new StreamContent(result.BlobStream) | |
}; | |
// Set content headers | |
message.Content.Headers.ContentLength = result.BlobLength; | |
message.Content.Headers.ContentType = new MediaTypeHeaderValue(result.BlobContentType); | |
message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") | |
{ | |
FileName = HttpUtility.UrlDecode(result.BlobFileName), | |
Size = result.BlobLength | |
}; | |
return message; | |
} | |
catch (Exception ex) | |
{ | |
return new HttpResponseMessage | |
{ | |
StatusCode = HttpStatusCode.InternalServerError, | |
Content = new StringContent(ex.Message) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment