简体   繁体   English

如何通过reactjs中的javascript下载文件

[英]How to download file through javascript in reactjs

I have a link /api/ticket/1/download to my server and if I copy paste it into the browser, it will start a download of my file with it's filename extension and everything set up already.我有一个链接 /api/ticket/1/download 到我的服务器,如果我将它复制粘贴到浏览器中,它将开始下载我的文件及其文件扩展名和所有设置。

How can I do it in javascript?如何在 javascript 中做到这一点? With thymeleaf i was just using <a href="myLink"> and it worked like if I paste it in the browser.使用thymeleaf我只是在使用<a href="myLink">它就像我将它粘贴到浏览器中一样。 But due to react-router a href just goes to another page.但是由于react-router a href只是转到另一个页面。 But if I use await fetch like this:但是,如果我像这样使用await fetch

let url1 = '/api/ticket/' + fileId + '/download';
        const response = await fetch(url1);
        const blob = response.blob();
        const url = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `file.jpg`);
        document.body.appendChild(link);
        link.click();

i can transfer response into blob, but then i miss the files name and extension.我可以将响应传输到 blob,但是我错过了文件名和扩展名。

The only way to solve this that i found is: send file name and extension in a response header and than parse them manualy.我发现解决这个问题的唯一方法是:在响应 header 中发送文件名和扩展名,然后手动解析它们。 like: in spring:比如:在 spring 中:

myControllerMethod( HttpServletResponse response){
...
 response.setContentType(att.getType());
 response.setHeader("Content-Disposition", "attachment; filename=\"" + myFileName + "\"");
}

in react:反应:

const headers = response.headers;
const file = headers.get("Content-Disposition");

and then parse manully this 'file' to get filenamel;然后手动解析这个“文件”以获取文件名;

Try in this way, it may help you:尝试这种方式,它可能会帮助你:

fetch('http://localhost:8080/employees/download')
            .then(response => {
                response.blob().then(blob => {
                    let url = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.href = url;
                    a.download = 'employees.json';
                    a.click();
                });

For more reference you can go through This link如需更多参考,您可以通过 此链接go

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

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