Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a file in the HttpResponseMessage Content?

I want to return a file in an HttpResponseMessage Content something like this:

return Request.CreateResponse(HttpStatusCode.OK, {{a file here}});

Or this:

return new HttpResponseMessage() {
   StatusCode = HttpStatusCode.OK; 
   Content = {{ a file "example.zip" here}}
};

Is this possible?

like image 885
A-Sharabiani Avatar asked Dec 03 '25 01:12

A-Sharabiani


1 Answers

You can use the System.Net.Http.HttpContent.StreamContent instance to add a FileStream object to the to the HttpResponseMessage's Content property. Something like this:

        // Return archive stream
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(fileStream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
            FileName = fileName.ToString()
        };

Note that you should probably also add a MD5 checksum to the file content in real applications.

like image 147
Jeff Hay Avatar answered Dec 04 '25 14:12

Jeff Hay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!