Download Binary from WebApi2 As File. Server Side

asp.net asp.net-web-api2 binaryfiles c# entity-framework-6

Popular Answer

You should be able to start now with this:

var response = new HttpResponseMessage(HttpStatusCode.OK) 
{ 
   Content = new StreamContent(new MemoryStream(fileByte))        
};
response.Content
        .Headers
        .Add("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
{ 
   FileName = "test.docx" 
};
return response;

Regarding recommendations for refactoring, you may employ my approach.

I've got a version of theIHttpActionResult When I get back, it seems as follows:

public class DocumentAttachmentResult : IHttpActionResult {
    private readonly string fileName;
    private readonly string mimeType;
    private readonly byte[] blob;

    public DocumentAttachmentResult(string fileName, string mimeType, byte[] blob) {
        this.fileName = fileName;
        this.mimeType = mimeType;
        this.blob = blob;
    }

    private HttpResponseMessage Execute() {
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new MemoryStream(this.blob)) };
        response.Content.Headers.Add("Content-Type", this.mimeType);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = this.fileName };
        return response;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
        return Task.FromResult(this.Execute());
    }
}

And this is how my controller is acting:

    [HttpGet]
    [Route("attachments/{id:guid}/download")]
    public IHttpActionResult DownloadAttachment(Guid id) {
        var attachment = this.repository.FindById(id);
        if (attachment == null) {
            return this.NotFound();
        }
        return new DocumentAttachmentResult(attachment.Name, attachment.FileType.MimeType, attachment.BinaryBlob);
    }

I model the file name, mime type, and binaries as a single object named in SQL server.Attachment . When I upload a file using a different action on my WebApi controller, the mime type and file are collected.

1
8/4/2015 7:19:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow