nodejs 点击按钮下载_nodejs实现文件下载

遇到个问题,由于和后端对接一个下载功能,第一次做不大会,所以使用了隐藏的form表单进行使用,成功下载,后来越想越不对。自己琢磨下,有了这篇博客😃

content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

Document

#download {

cursor: pointer;

}

点我下载

const btn = document.querySelector('#download');

btn.addEventListener('click', function (e) {

axios({

url: 'http://localhost:8086/getFile?filename=test.txt',

responseType: 'blob',

method: 'get',

}).then(function (response) {

// handle success

console.log(response);

})

.catch(function (error) {

// handle error

console.log(error);

})

.finally(function () {

// always executed

});

});

//download.js

const http = require('http');

const url = require('url');

const fs = require('fs');

const path = require('path');

const server = http.createServer((req, res) => {

const {pathname, query} = url.parse(req.url);

const urlStr = url.parse(req.url);

if (pathname === '/getFile') {

const queryObj = {};

if (query.length) {

const queryArr = query.split('&');

queryArr.forEach((e, i) => {

let oneQuery = e.split('=');

let key = oneQuery[0];

let value = oneQuery[1];

queryObj[key] = value;

});

}

const keys = Object.keys(queryObj);

let data;

keys.forEach(function (key) {

if (key === 'filename') {

let filepath = path.resolve(__dirname, queryObj[key]);

console.log(filepath);

fs.readFile(filepath, (err, data) => {

console.log('data....');

if (err) {

res.end(err);

return;

}

res.writeHead(200, {

'Content-Disposition': 'attachment; filename=' + queryObj[key],

'content-type': 'application/octet-stream',

'Access-Control-Allow-Origin': '*',

'Access-Control-Allow-Headers': 'X-Requested-With',

'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',

});

fs.createReadStream(filepath).pipe(res);

});

}

});

}

});

server.listen(8086);

未完待续.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值