Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download file from asp.net web api

i am trying to download a file (.docx) from asp.net web api.

Since i already have a document in the server i set the path to existing one and then i follow something sugested on stackoverflow and do this:

docDestination is my path.

   HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(docDestination, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    return result;

after that on my client side i try to do this:

    .then(response => {
            console.log("here lives the response:", response);
            var headers = response.headers;
            var blob = new Blob([response.body], { type: headers['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "Filename";
            link.click();
        }

this is what i get on my response

response

what i get:

what i get

any help?

like image 897
Filipe Costa Avatar asked Dec 07 '22 17:12

Filipe Costa


1 Answers

Just add ContentDisposition to your response header with value of attachment and the browser will interpret it as a file that needs to be download

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(docDestination, FileMode.Open,FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "document.docx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 
return result;

Take a look in this link for more information in ContentDisposition header

like image 110
Christopher Enriquez Avatar answered Dec 11 '22 09:12

Christopher Enriquez