0

Helo, i already search on Google and here (StackOverflow) but no any solution i complete.

I Have a Excel file in my folder and i need to create a method on my controller to download this file.

And in my React Web Site i need to get this file to user computer.

I try to use ActionResult, FileStreamResult, HttpResponseMessage and other, read file from folder with File.ReadAllbytes, put the Header on response.

On the final i get this.

{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}

And using this JavaScript do download:

var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
                var blob = new Blob([bytes], {
                    type: responseDownloadFile.data.ContentType
                });

                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = responseDownloadFile.data.FileDownloadName;
                document.body.appendChild(link);
                link.click();

But the file when download is corrupted.

Any on can help me?

2

1 Answer 1

0

Try to return HttpResponseMessage type on your API

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent([file bytes]);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "filename.xlsx"
            };

            return result;

And on your Front end execute code:

window.location.href = "link to your api endpoint to download excel";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.