后端如果返回一个文件的地址,前端实现下载,可以借助原生ajax来实现
实现代码如下所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="button" value="test" onclick="test()"> <script> const fileInfo = { url: 'pdf/5ea56710fb5a2fdad7cabcf3.pdf', name: 'b.pdf' } function test() { downloadUrlFile(fileInfo.url) } function downloadUrlFile(url) { const xhr = new XMLHttpRequest() xhr.open('GET', url, true) xhr.responseType = 'blob' xhr.onload = () => { if (xhr.status === 200) { saveAs(xhr.response, fileInfo.name) } } xhr.send() } function saveAs(data, name) { var urlObject = window.URL || window.webkitURL || window; var export_blob = new Blob([data]); var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a') save_link.href = urlObject.createObjectURL(export_blob); save_link.download = name; save_link.click(); } </script> </body> </html>