Recently, I was working on a browser to download files, and I encountered a strange problem. "The browser has received the response from the server, and you can see that it is continuously receiving data, but the download prompt box does not pop up."
At first, the guess is that there is a problem with the response header of the server:
server code
// 文件下载
app.get('/fm/download', (req, res) => {
const { target } = req.query;
if (target) {
const file_path = connector.decode(target);
const rs = fs.createReadStream(file_path);
res.setHeader(
'Content-Disposition',
`attachment; filename=${file_path.split('/').pop()}`
);
rs.pipe(res);
} else {
res.send({ success: false, msg: '下载路径不合法' });
}
});
The server uses the express framework to return the file to the front end in the form of a stream.
Later inspired by stackoverflow , it is not a server-side problem, but because the front-end uses ajax requests .
If you use a library like axios to request the download interface, although the data can be received, the download pop-up window of the browser cannot be invoked.
Solution
You can use window.open(download_url) to open a new browser tab to download, or window.location to point to the download link.
async DownloadFile() {
window.open(downLoadUrl)
}
In this way, the browser can normally pop up the download pop-up box.
Finally, I hope this article can help you. If you find it useful, please help to like and collect, thank you! ❤️❤️
The article was first published on IICCOM's technical blog "Content-Disposition: attachment did not trigger the browser download popup"
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。