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

我有一个链接 /api/ticket/1/download 到我的服务器,如果我将它复制粘贴到浏览器中,它将开始下载我的文件,它的文件扩展名和一切都已经设置好了。


我怎样才能在 javascript 中做到这一点?随着thymeleaf我只是用<a href="myLink">它的工作一样,如果我把它粘贴到浏览器中。但由于react-router a href只是转到另一个页面。但如果我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();

我可以将响应传输到 blob,但随后我错过了文件名和扩展名。


蓝山帝景
浏览 263回答 2
2回答

慕尼黑5688855

我发现解决这个问题的唯一方法是:在响应头中发送文件名和扩展名,然后手动解析它们。像:在春天:myControllerMethod( HttpServletResponse response){...&nbsp;response.setContentType(att.getType());&nbsp;response.setHeader("Content-Disposition", "attachment; filename=\"" + myFileName + "\"");}在反应:const headers = response.headers;const file = headers.get("Content-Disposition");然后手动解析这个“文件”以获取文件名;

哈士奇WWW

以这种方式尝试,它可能会帮助您:fetch('http://localhost:8080/employees/download')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(response => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.blob().then(blob => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let url = window.URL.createObjectURL(blob);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let a = document.createElement('a');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.href = url;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.download = 'employees.json';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.click();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript