NodeJS 使用 multiparty 实现文件上传

使用中间件 multiparty

npm 文档

安装

npm install multiparty

multiparty.Form

var form = new multiparty.Form(options)

Options:

  • encoding - sets encoding for the incoming form fields. Defaults to utf8.
  • maxFieldsSize - Limits the amount of memory all fields (not files) can allocate in bytes. If this value is exceeded, an error event is emitted. The default size is 2MB.
  • maxFields - Limits the number of fields that will be parsed before emitting an error event. A file counts as a field in this case. Defaults to 1000.
  • maxFilesSize - Only relevant when autoFiles is true. Limits the total bytes accepted for all files combined. If this value is exceeded, an error event is emitted. The default is Infinity.
  • autoFields - Enables field events and disables part events for fields. This is automatically set to true if you add a field listener.
  • autoFiles - Enables file events and disables part events for files. This is automatically set to true if you add a file listener.
  • uploadDir - Only relevant when autoFiles is true. The directory for placing file uploads in. You can move them later using fs.rename(). Defaults to os.tmpdir().

使用实例

var multiparty = require('multiparty');
var http = require('http');
var util = require('util');
var fs = require('fs');
console.log(__dirname);
//注意权限问题
var path = __dirname + '/images/';
http.createServer(function(req, res) {
    if (req.url === '/upload' && req.method === 'POST') {
        //设置编码格式和上传路径。默认上传路径是os.tmpdir(),可以启动node环境输入查看
        var form = new multiparty.Form({ encoding: 'utf-8', uploadDir: path });
        form.parse(req, function(err, fields, files) {
            var filesTmp = JSON.stringify(files, null, 2);
            if (err) {
                console.log('parse error: ' + err);
            } else {
                console.log('parse files: ' + filesTmp);
                // upload 需要与网页中的input的name属性相同
                for (var i in files.upload) {
                    var inputFile = files.upload[i];
                    var uploadedPath = inputFile.path;
                    var dstPath = path+inputFile.originalFilename;
                    //重命名为真实文件名
                    fs.rename(uploadedPath, dstPath, function(err) {
                        if (err) {
                            console.log('rename error: ' + err);
                        } else {
                            console.log('rename ok');
                        }
                    });
                }
            }
            res.writeHead(200, { 'content-type': 'text/plain' });
            res.write('received upload:\n\n');
            res.end(util.inspect({ fields: fields, files: files }));
        });
        return;
    }
    // show a file upload form ,注意此处测试时设置utf-8,否则获取的文件名乱码,正常使用一般都是结合expess了
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
    res.end(
        '
' + '
' + '
' + '' + '
' ); }).listen(3000);

你可能感兴趣的:(NodeJS 使用 multiparty 实现文件上传)