这是我到目前为止从服务器下载文件所做的。问题是我不知道在响应函数内写什么,以使文件像大多数网站下载一样自动下载。如果我写console.log(response)
我在console.log中看到该文件为字符串我想要下载它。
客户端
function downloadFile(filePath) {
return $http({
url: '/download',
method: "GET",
params: { filePath: filePath }
}).then((response) => {
return response.data;
}).catch(err => console.err);
}
function fileDownload(filePath, fileExtension) {
let filepath = filePath + '.' + fileExtension;
downloadFile(filepath).then((response) => {
});
}
服务器:
app.get('/download', (req, res) => {
let file = path.join(__dirname, 'public/files' , req.query.filePath);
res.download(file);
});
答案 0 :(得分:0)
app.get('/download', (req, res) => {
let file = path.join(__dirname, 'public/files' , req.query.filePath);
let mime_type // check https://en.wikipedia.org/wiki/MIME#Content-Type
, disposition // check https://en.wikipedia.org/wiki/MIME#Content-Disposition
;
let header = {
'Content-Type': mime_type,
'Content-Disposition': disposition
}
let fReadStream = fs.createReadStream(file);
fReadStream.on('open', (fd) => {
res.writeHeader(200, header);
}).pipe(res);
});