Node.js 上传文件

Formidable 模块

有一个非常好的模块用于处理文件上传,名为“Formidable”。

可以使用 NPM 下载和安装 Formidable 模块:

C:\Users\Your Name>npm install formidable
下载 Formidable 模块后,您可以将该模块包含在任何应用程序中:

var formidable = require('formidable');

上传文件
现在,您已准备好在 Node.js 中创建一个网页,让用户将文件上传到您的计算机:

步骤 1:创建上传表单

创建一个 Node.js 文件,该文件写入带有上传字段的 HTML 表单:

示例获取您自己的 Node.js 服务器
此代码将生成一个 HTML 表单:

var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);

步骤 2:解析上传的文件

包含 Formidable 模块,以便在文件到达服务器后能够解析上传的文件。

当文件上传并解析后,它将被放置在计算机上的临时文件夹中。

示例
文件将被上传并放置在临时文件夹中:

var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('文件已上传');
res.end();
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);

步骤 3:保存文件

当文件成功上传到服务器时,它将被放置在临时文件夹中。

此目录的路径可以在“files”对象中找到,该对象作为 parse() 方法的回调函数中的第三个参数传递。

要将文件移动到您选择的文件夹,请使用文件系统模块并重命名文件:

示例
包含 fs 模块,并将文件移动到当前文件夹:

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('文件已上传并移动!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);

总结

本文介绍了Node.js上传文件,如有问题欢迎私信和评论

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐