NodeJS 使用 multiparty 實(shí)現(xiàn)文件上傳

使用中間件 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().

使用實(shí)例

var multiparty = require('multiparty');
var http = require('http');
var util = require('util');
var fs = require('fs');
console.log(__dirname);
//注意權(quán)限問題
var path = __dirname + '/images/';
http.createServer(function(req, res) {
    if (req.url === '/upload' && req.method === 'POST') {
        //設(shè)置編碼格式和上傳路徑。默認(rèn)上傳路徑是os.tmpdir(),可以啟動(dòng)node環(huán)境輸入查看
        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 需要與網(wǎng)頁中的input的name屬性相同
                for (var i in files.upload) {
                    var inputFile = files.upload[i];
                    var uploadedPath = inputFile.path;
                    var dstPath = path+inputFile.originalFilename;
                    //重命名為真實(shí)文件名
                    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 ,注意此處測(cè)試時(shí)設(shè)置utf-8,否則獲取的文件名亂碼,正常使用一般都是結(jié)合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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容