一、后端(Nodejs)
1、示例代码
const http = require('http');
const fs = require('fs');
const port = 8080;
const server = http.createServer((req, res) => {
const { method } = req;
res.setHeader('Access-Control-Allow-Origin', '*');
if (method === 'GET') {
res.setHeader('Content-Disposition', 'attachment;filename=ooo.jpg');
const imgRs = fs.createReadStream('./images/001.jpg');
imgRs.pipe(res)
}
})
server.listen(port, () => {
console.log(`Server is running at localhost:${port}...`);
})
二、前端
1、直接使用a标签实现下载
<!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>
<a href="http://localhost:8080">下载</a>
</body>
</html>
2、ajax下载文件
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080');
xhr.responseType = 'blob';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const xhrRes = xhr.response;
const fileReader = new FileReader();
fileReader.onload = function () {
const resultBase64 = fileReader.result;
const a = document.createElement('a');
a.href = resultBase64;
a.download = 'xixi.jpg';
a.click();
}
fileReader.readAsDataURL(xhrRes);
}
}
xhr.send(param);
- 该方式的思路主要是从后端获取到文件数据后,前端对数据进一步处理,处理方式除了上述的FileReader,还可以使用URL接口的静态方法createObjectURL,代码如下:
const objUrl = URL.createObjectURL(xhrRes);
console.log(objUrl)
const a = document.createElement('a');
a.href = objUrl;
a.download = 'xixi.jpg';
a.click();
- 需要注意的是,在每次调用URL.createObjectURL()方法时,都会创建一个新的URL对象,该URL对象的生命周期和创建它的窗口的document绑定,浏览器在document卸载的时候,会自动释放它们,但是为了获得最佳性能和内存使用状况,你应该在安全的时机调用URL.revokeObjectURL()方法主动释放掉它们。