Node.js 文件上传
Formidable 模块
有一个非常好的用于处理文件上传的模块,称为 "Formidable"。
可使用 NPM 下载和安装 Formidable 模块:
C:\Users\ Your Name >npm install formidable
下载 Formidable 模块后,您可以将该模块引用在任何应用程序中:
var formidable = require('formidable');
上传文件
现在,您可以在 Node.js 中创建网页,让用户可以将文件上载到您的电脑:
第 1 步 : 创建 Upload 表单
创建一个 Node.js 文件写入带有 upload(上传)字段的 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);
第 2 步 : 解析上传的文件
引用 Formidable 模块,使上传的文件到达服务器后可以解析该文件。
上传和解析文件后,它会被放置在计算机上的临时文件夹中。
实例
将上传该文件,并将其放置在临时文件夹中:
var http = require('http');<strong>var formidable = require('formidable');</strong>http.createServer(function (req, res) {<strong> if (req.url == '/fileupload') {var form = new formidable.IncomingForm();form.parse(req, function (err, fields, files) {res.write('File uploaded');res.end();});</strong> } 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');<strong>var fs = require('fs');</strong>http.createServer(function (req, res) {if (req.url == '/fileupload') {var form = new formidable.IncomingForm();form.parse(req, function (err, fields, files) {<strong> 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();});</strong> });} 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);