How to correctly download files to Angular from ASP.NET Core?

前端 未结 3 1202
粉色の甜心
粉色の甜心 2020-12-12 00:25

I have a file on the server that I want to send to the client:

[HttpPost]
public IActionResult Test()
{
    byte[] bytes = System.IO.File.ReadAllBytes(Path.C         


        
3条回答
  •  醉话见心
    2020-12-12 00:49

    I do not know why the option specified in the question does not work. But I found a solution, so to say "in another forest". I'm not very versed, so I'll just describe the process of solving the problem. For the beginning I will immediately say that the problem was on the client's side. The method on the server worked correctly from the start. I decided to use another method to download the files "fetch". And came across the next post in the forum. From there I took the following answer

    this.httpClient
        .fetch(url, {method, body, headers})
        .then(response => response.blob())
        .then(blob => URL.createObjectURL(blob))
        .then(url => {
            window.open(url, '_blank');
            URL.revokeObjectURL(url);
        });
    

    He did not work for me either. I changed it so

        fetch(url, {
                method: 'POST',
                headers: this.headers()
            })
            .then(response => response.blob())
            .then(blob => URL.createObjectURL(blob))
            .then(url => {
                window.open(url, '_blank');
            });
    

    Because of this line nothing happened

    URL.revokeObjectURL(url);
    

    This option worked, but with screwed. He saved the file with a strange name and no extension. Then I changed it so.

        fetch(url, {
                method: 'POST',
                headers: this.headers()
            })
                .then(response => response.blob())
                .then(blob => URL.createObjectURL(blob))
                .then(url => {
                    var link = document.createElement("a");
                    link.setAttribute("href", url);
                    link.setAttribute("download", "test.docx");
                    link.style.display = "none";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                });
    

    And it works! I apologize for the English. I'm using Google translator

提交回复
热议问题