Node.js 如何处理文件上传
可以通过使用Formidable来轻松进行文件上传。Formidable是一个可以通过在项目目录中键入命令来安装的模块。
npm install formidable
步骤: 我们需要使用HTTPS模块设置一个服务器,使用表格上传文件,使用Formidable模块将上传的文件保存在临时位置,最后使用文件系统模块将文件移动到我们的项目文件夹中。
步骤1:导入HTTP模块、Formidable模块和文件系统模块
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
步骤2:创建上传文件的表单
http.createServer((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);
步骤3:使用Formidable模块将文件上传到临时文件夹
我们需要创建一个变量来处理传入的表单数据,然后解析数据。我们还将使用 files 参数来获取有关上传文件的详细信息,如 filepath 用于获取Formidable模块临时存储的文件的路径, originalFilename 用于获取上传文件的实际文件名。
var form = new formidable.IncomingForm()
form.parse(req, function (err, fields, files) {
var tempFilePath = files.filetoupload.filepath;
var projectFilePath = __dirname + '/uploaded_file/'
+ files.filetoupload.originalFilename;
});
步骤4:将上传的文件移动到项目文件夹中
fs.rename(tempFilePath, projectFilePath, function (err) {
if (err) throw err;
res.write('File has been successfully uploaded');
res.end();
});
App.js
const http = require('http');
const formidable = require('formidable');
const 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 tempFilePath = files.filetoupload.filepath;
var projectFilePath = __dirname + '/uploaded_file/' +
files.filetoupload.originalFilename;
fs.rename(tempFilePath, projectFilePath, function (err) {
if (err) throw err;
res.write('File has been successfully uploaded');
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 app.js
输出: