您现在的位置是:网站首页> 编程资料编程资料
Node.js实现下载文件的两种实用方式_node.js_
2023-05-24
363人已围观
简介 Node.js实现下载文件的两种实用方式_node.js_
第一种方式:使用原生的http模块
我们仅需要用到fs和http两个node.js的原生模块,不需要安装第三方模块,就可以实现文件的下载。代码如下:
var fs = require('fs'); var http = require("http"); var server = http.createServer(); server.on("request", function (request, response) { // 获取请求URL var url = request.url; // 如果是下载文件的URL,则判断进行处理 if (url === '/download/hello.txt') { // 提取文件名hello.txt var name = url.substring(url.lastIndexOf('/')); // 创建可读流,读取当前项目目录下的hello.txt文件 var rs = fs.createReadStream(__dirname + "/" + name); // 设置响应请求头,200表示成功的状态码,headers表示设置的请求头 response.writeHead(200, { 'Content-Type': 'application/force-download', 'Content-Disposition': 'attachment; filename=' + name }); // 将可读流传给响应对象response rs.pipe(response); } }); server.listen(8888, function () { console.log("服务器启动成功,可以通过 http://127.0.0.1:8888 来进行访问"); }); 然后可以通过http://127.0.0.1:8888/download/hello.txt下载文件。

第二种方式:使用Express+Axios下载文件
前端通过axios发送GET或者POST请求来进行文件的下载,关键是对响应回来的文件数据进行处理。
index.html:前端页面,通过点击按钮来进行下载文件,而请求是通过axios来发送的。
index.js:使用express来渲染index.html页面,并且来处理下载请求。
var fs = require('fs'); var express = require('express'); var app = express(); // 渲染index.html,跟下载逻辑无关 app.get('/index.html', function (request, response) { fs.readFile('index.html', function (err, data) { if (!err) { response.end(data); } }); }); // 处理下载文件的请求 app.post('/file/download', function (request, response) { var name = "hello.txt";// 待下载的文件名 var path = __dirname + "/" + name;// 待下载文件的路径,指定为当前项目目录下的hello.txt文件 var f = fs.createReadStream(path); response.writeHead(200, { 'Content-Type': 'application/force-download', 'Content-Disposition': 'attachment; filename=' + name }); f.pipe(response); }); // 监听端口,相当于原来的server.listen() app.listen(8888, function () { console.log("app is running at port 8888."); }); 
又可以通过response.set()方法来设置响应头:
response.set({ 'Content-Type': 'application/octet-stream',// 告诉浏览器这是一个二进制文件 'Content-Disposition': 'attachment; filename=' + name// 告诉浏览器这是一个需要下载的文件 }); 总结
下载文件其实很简单,在哪种语言里都是这样:
第一步,设置响应头。第二步,返回数据流。
设置响应头
下载文件需要设置的响应头是Content-Type和Content-Disposition,响应头与编程语言无关,是通用的。
'Content-Type': 'application/octet-stream'表示这是一个二进制文件。
'Content-Disposition': 'attachment;filename=hello.txt'表示这是一个需要下载的附件,并且告诉浏览器默认文件名。
返回数据流
读取要下载的文件,以二进制流的形式响应给客户端。
到此这篇关于Node.js实现下载文件的两种实用方式的文章就介绍到这了,更多相关Node.js下载文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- @vue/cli4升级@vue/cli5 node.js polyfills错误的解决方式_vue.js_
- js通过var定义全局变量与在window对象上直接定义属性的区别说明_javascript技巧_
- 如何使用moment.js获取本周、前n周、后n周开始结束日期及动态计算周数_javascript技巧_
- Vue取消Axios发出的请求_vue.js_
- 一文带你快速学会JavaScript条件判断及高级用法_javascript技巧_
- JavaScript三种获取URL参数值的方法_javascript技巧_
- JS中的art-template模板如何使用if判断_javascript技巧_
- Vue2为何能通过this访问到data与methods的属性_vue.js_
- elementUI+Springboot实现导出excel功能的全过程_vue.js_
- vue-cli3启动服务如何自动打开浏览器配置_vue.js_
