简体   繁体   English

从 ReactJs 中的 api 下载文件

[英]Download file from api in ReactJs

I have ASP.NET Core MVC back-end api.我有 ASP.NET 核心 MVC 后端 api。 One controller returns File from server.一个 controller 从服务器返回文件。 Is there a way to make request to api route by [href] attribute of <a> tag?有没有办法通过 <a> 标签的 [href] 属性向 api 路由发出请求? Looks like it tries to call React route but not make a request to server.看起来它试图调用 React 路由但没有向服务器发出请求。

Also I made AJAX call to that controller and got back file as a string (screenshot is attached).此外,我对 controller 进行了 AJAX 调用,并将文件作为字符串返回(附有屏幕截图)。 Why is it a string, shouldn.t it be a byte array?为什么它是一个字符串,不应该是一个字节数组? How to build back file from that string?如何从该字符串构建回文件? (it's a.pdf file). (这是一个.pdf 文件)。 I have an empty PDF if use JavaScript new File([], 'name', {options}).如果使用 JavaScript new File([], 'name', {options}),我有一个空的 PDF。

ASP.NET Core controller returns PDF this way: ASP.NET 内核 controller 以这种方式返回 PDF:

return PhysicalFile(Path.GetFullPath(relativePath), "application/pdf", reportName);

In React I receive it as a string this way:在 React 中,我以这种方式将其作为字符串接收:

let stringPDFBinary = await ReportService.getReport(id, reportFileName)

I just need to download file from api by any way.我只需要以任何方式从 api 下载文件。 在此处输入图像描述

So, the answer is here: PDF is blank when downloading using javascript所以,答案就在这里: PDF is blank when download using javascript

The same problem.同样的问题。 Let it be one more topic, easier to find for others.让它成为另一个主题,更容易为其他人找到。 The AJAX response is encoded string. AJAX 响应是编码字符串。 In request config set 'responseType = 'arraybuffer'' somehow and receiving pdf will not be blank.在请求配置中设置'responseType ='arraybuffer''以某种方式接收 pdf 不会为空。 Solved.解决了。

I Just copied and pasted from the code source.我只是从代码源中复制并粘贴。 The problem seems to be the same that i had:问题似乎和我一样:

Asp net controller: ASP网controller:

    [HttpGet]
    [Route("File")]
    [AllowAnonymous]
    public IActionResult GetFile(string key)
    {
        var file = (FileCacheValue)_fileCache.Cache[key.Replace(" ", "+")];

        if (file == null)
            return NotFound();

        Response.Headers["content-disposition"] = $"inline;filename={file.Name}.pdf";

        return File(file.Data, "application/pdf");
    }

In this case comes from a cache system.在这种情况下来自缓存系统。 The data is a byte array.数据是一个字节数组。

Front-end React:前端反应:

const onClick = () => 
{
   window.open(pdfByteArray, '_blank', 'fullscreen=yes');
}

Exactly what i have.正是我所拥有的。 I just put the data on a new window and open the pdf.我只是把数据放在一个新的 window 上,然后打开 pdf。

The Ajax part is straight forward, get the value from the response and set it on a variable Ajax 部分很简单,从响应中获取值并将其设置在变量上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM