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(
        '<form action="/upload" enctype="multipart/form-data" method="post">' +
        '<input type="text" name="title"><br>' +
        '<input type="file" name="upload" multiple="multiple"><br>' +
        '<input type="submit" value="Upload">' +
        '</form>'
    );
}).listen(3000);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,938评论 0 0
  • 如果,你错过了绚丽绽放的烟花 别忘了,黑夜下 浩瀚无垠的星空在等你 如果,你错了激荡回旋的流水 别忘了,大海里 那...
    请你不要难过阅读 182评论 1 2
  • 文/梓星 七岁那年 我还是扎着麻花辫 穿着碎花裙的小姑娘 月光下我会追着自己的影子跑 却怎么也追不到 十七岁那年 ...
    梓莘阅读 242评论 3 10
  • https://leetcode.com/tag/depth-first-search/ https://leet...
    丁不想被任何狗咬阅读 372评论 0 0
  • 无规矩不成方圆,无论在哪里都有其规矩,监狱则更加明显,将规矩放大,守规矩就有好日子过,要不然就会受到群起攻之。梁朝...
    电影聚焦阅读 5,496评论 1 2