问题描述:
打开一个链接不是提示下载文件而是直接用浏览器打开。
实现效果:
弹出下载框,然后选择本地存储路径进行保存。
实现浏览器下载而非打开文件
var e = document.createElement('a');
e.href = 'http://zhangdanyang.com/filename.md';
e.download = 'filename.md';
e.click();
与NodeJS相结合
实现流程:
- 后端生成文件并将文件路径返回给前端。 * 前端动态创建a元素, 使其href属性指向文件路径, 并添加download属性。 * 模拟其点击事件以实现下载。
实例展示
前端
var params = {
'title': this.post.title,
'category': this.post.category,
'content': this.post.content,
'tags': this.post.tags
}
this.$axios.post('/save', params).then(function(response) {
console.log(response);
console.log(window.location.origin, response.data)
var e = document.createElement('a');
e.href = window.location.origin.replace('8080', '3333') + '/' + response.data;
e.download = (params.title || 'NoTitle') + '.md';
e.click();
}).catch(function(error) {
// console.log(error);
// that.error = error.toString()
that.error = true;
that.loading = false;
})
后端
【 app.js】
var save = require('./save');
app.use(express.static(path.join(__dirname, 'files')));
//保存到本地
app.post('/save', function(req, res) {
var post = {
'title': req.body.title,
'content': req.body.content,
'category': req.body.category,
'tags': req.body.tags
};
save.save(post, function(fileName) {
// 解决方案
res.send(fileName)
// 方案1:测试无效,起码 .md 无效
// var stats = fs.statSync(filePath);
// if (stats.isFile()) {
// res.set({
// 'Content-Type': 'application/octet-stream',
// 'Content-Disposition': 'attachment; filename=' + fileName,
// 'Content-Length': stats.size
// });
// fs.createReadStream(filePath).pipe(res);
// } else {
// res.end(404);
// }
// 方案2:测试无效,起码 .md 无效
// res.download(filePath, fileName, function(err) {
// if (err) {
// // Handle error, but keep in mind the response may be partially-sent
// // so check res.headersSent
// } else {
// // decrement a download credit, etc.
// }
// });
}, function() {
res.end(404);
});
});
【 save.js】
var fs = require('fs');
var save = {
save: function(param, callback, callerr) {
var title = param.title || '';
var category = param.category || '';
var tags = param.tags || '';
var content = param.content || '';
var filename = (title || 'NOTITLE') + '(' + Date.now() + ')' + '.md';
var con = "---\r\ntitle: " + title + "\r\ncategory: " + category + "\r\ntags: " + tags + "\r\n---\r\n" + content;
fs.writeFile('files/' + filename, con, (err) => {
if (err) {
callerr && callerr();
throw err;
return;
}
console.log('The file has been saved!');
callback && callback(filename);
});
}
}
// var param={
// title:'',
// category:'',
// tags:'',
// content:''
// }
// save.save(param);
module.exports = save;