簡體   English   中英

NodeJS Multer:未應用配置

[英]NodeJS Multer: configuration not applied

我有一個使用Multer用NodeJS編寫的簡單上傳應用程序,效果很好。 這是代碼:

var express = require('express'),
    bodyParser = require('body-parser'),
    qs = require('querystring'),
    multer = require('multer'),
    logger = require('morgan');

var config = require('./config'),
    oauth = require('./oauth');

function extractExtension(filename) {
    return filename.split('.').pop();
}

function getRandom(min, max) {
    return Math.floor(Math.random() * max) + min;
}


var app = express();
//app.use(cors());

// Add headers
app.use(function(req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Authorization,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

// Multer
var momentUpload = multer({
    dest: './uploads/',
    limits: {
        fileSize: 256 * 1024 * 1024
    },
    rename: function(fieldname, filename) {
        return Date.now() + '-' + getRandom(100000, 999999) + '.' + extractExtension(filename);
    },
    onFileUploadStart: function(file) {
        console.log(file.originalname + ' is starting ...')
    },
    onFileUploadComplete: function(file) {
        console.log(file.fieldname + ' uploaded to  ' + file.path)
    }
}).single('file');

app.set('port', 4000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.post('/file/upload', [oauth.ensureAuthenticated, momentUpload, function(req, res) {
    console.log(req.body); // form fields
    console.log(req.file); // form files

    res.status(204).end();
}]);

// Start the Server
app.listen(app.get('port'), function() {
    console.log('Metadata store env: ' + config.METADATASTORE_ENV);

    console.log('Express server listening on port ' + app.get('port'));

    firebase.authenticate();
    console.log('Connected to Firebase');
});

問題是,Multer的配置似乎根本不起作用。 destPath有效,文件顯示在我提供的文件夾(./uploads/)中。 允許使用更大的文件大小(例如,文件大小為400MB,而選項明顯為256MB),並且不會觸發一次回調函數。 沒有錯誤信息。 知道我在做什么錯嗎? 我遵循了Google和官方頁面上的指南,但無法正常工作。

首先,multer最近改變了它的API,因此它不再接受renameonFileUploadStartonFileUploadComplete

我們可以在這里https://github.com/expressjs/multer上查看API,因此讓我們分析一下工作的新方式!

注意:如果您尚未更新multer版本,強烈建議您進行更新,因為懷疑舊版本存在安全漏洞。

基本用法

Multer接受一個options對象,其中最基本的是dest屬性,它告訴Multer在哪里上傳文件。 如果省略options對象,文件將保留在內存中,並且永遠不會寫入磁盤。

默認情況下,Multer將重命名文件,以避免命名沖突。 重命名功能可以根據您的需求進行定制。 options對象還接受fileFilter (用於控制上傳文件的功能)和limits (指定大小限制的對象)參數。

因此,您的代碼將如下所示(僅涉及混合器部分,並考慮使用所有不必使用的選項):

// Multer
var momentUpload = multer({
    dest: './uploads/',
    limits: {
        fileSize: 256 * 1024 * 1024
    },
    fileFilter: function(req, file, cb) {

        // The function should call `cb` with a boolean
        // to indicate if the file should be accepted

        // To reject this file pass `false`, like so:
        cb(null, false)

        // To accept the file pass `true`, like so:
        cb(null, true)

        // You can always pass an error if something goes wrong:
        cb(new Error('I don\'t have a clue!'))

    }
}).single('file');

如果您想更好地控制文件的存儲,可以使用存儲引擎。 您可以創建自己的文件,也可以簡單地使用可用的文件。

可用的有: diskStorage用於將文件存儲在磁盤或memoryStorage用於將文件存儲在內存中作為Buffer對象。

由於您顯然想將文件存儲在磁盤中,因此讓我們來談談diskStorage

有兩個選項: destinationfilename

destination用於確定上傳的文件應存儲在哪個文件夾中。 這也可以作為字符串給出(例如'/ tmp / uploads')。 如果未指定目的地,則使用操作系統的臨時文件默認目錄。

注意:當提供目標功能時,您負責創建目錄。 傳遞字符串時,multer將確保為您創建目錄。

filename用於確定應在文件夾內命名的文件。 如果未提供文件名,則將為每個文件分配一個不包含任何文件擴展名的隨機名稱。

因此,您的代碼(僅涉及multer部分)如下所示:

// Multer
//Storage configuration
var storageOpts = multer.diskStorage({
    destination: function (req, file, cb) {
        //Choose a destination
        var dest = './uploads/';

        //If you want to ensure that the directory exists and 
        //if it doesn't, it is created you can use the fs module
        //If you use the following line don't forget to require the fs module!!!
        fs.ensureDirSync(dest);
        cb(null, dest);
    },
    filename: function (req, file, cb) {

        //here you can use what you want to specify the file name
        //(fieldname, originalname, encoding, mimetype, size, destination, filename, etc)
        cb(null, file.originalname);
    }
});

var momentUpload = multer({
    storage: storageOpts,
    limits: {
        fileSize: 256 * 1024 * 1024
    },
    fileFilter: function(req, file, cb) {

        // The function should call `cb` with a boolean
        // to indicate if the file should be accepted

        // To reject this file pass `false`, like so:
        cb(null, false)

        // To accept the file pass `true`, like so:
        cb(null, true)

        // You can always pass an error if something goes wrong:
        cb(new Error('I don\'t have a clue!'))

   }
}).single('file');

希望能有所幫助! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM