有一个非常好的用于文件上传的模块,称为"Formidable"。
Formidable 模块可以使用 NPM 下载并安装:
C:\Users\
Your Name>npm install formidable
下载 Formidable 模块后,您可以将该模块包含在任何应用程序中:
var formidable = require('formidable');
现在您已准备好在 Node.js 中制作一个网页,让用户将文件上传到您的计算机:
创建一个 Node.js 文件,该文件写入 HTML 表单,并带有上传字段:
此代码将生成一个 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);
包含 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('File 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);
文件成功上传到服务器后,会被放置在临时文件夹中。
该目录的路径可以在 "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('File uploaded and moved!');
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);
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!