【问题标题】:How to define max uploaded file size & allowed file types in NodeJs restify bodyParser?如何在 NodeJs restify bodyParser 中定义最大上传文件大小和允许的文件类型?
【发布时间】:2016-12-15 17:35:59
【问题描述】:

我是 node.js 的新手。我已经使用 Restify 模块将图像文件上传到 Rest 服务器。但现在,我需要确保我上传的图像文件大小和 bodyParser 中允许的文件类型重新确定。

我的重置代码是:

var restify = require('restify'),
    fsEx = require('fs-extra'),
    md5 = require("md5"),
    path = require("path");

var server = restify.createServer({
    name: 'Photo Upload api server'
});

server.use(restify.bodyParser({
    maxBodySize: 2,
    mapParms: true,
    mapFiles: true,
    keepExtensions: true
}));


server.post('/resized', function(req, res, next) {

    var tempPath = req.files.photos.path;
    var getFileExt = path.extname(tempPath);
    var finalFileName = Date.now() + getFileExt;
    var finalImgPath = __dirname + "/uploads/" + finalFileName;

    fsEx.move(tempPath, finalImgPath, function(err) {

        if (err) {
            return console.error(err);
        }


    });

    console.log('result FinalImage = ', finalImgPath);

    res.end('image resized');
    next();
});

【问题讨论】:

    标签: node.js restify


    【解决方案1】:
    const maximumImageSize = 1 * 1024 * 1024;
    const allowedImageFormats = ['.png', '.jpg', '.jpeg'];
    
    const isValidImageFormat = (extension) => _.includes(allowedImageFormats, _.toLower(extension));
    const isValidImageSize = (size) => size < maximumImageSize;
    
    const imageExtension = path.extname(file.name);
    if (!isValidImageFormat(imageExtension)) {
        return next(new restify.errors.ForbiddenError('Invalid image format.'));
    }
    
    const imageSize = Number(req.headers['content-length']);
    if (!isValidImageSize(imageSize)) {
        return next(new restify.errors.ForbiddenError('Image is too big.'));
    }
    

    【讨论】:

    • 好主意,但content-length 不是图像大小,而是身体大小。
    • 是的。此代码来自端点仅上传单个图像的项目,因此在这种情况下它可以工作。但你是对的,如果正文包含的不仅仅是图像,则需要执行其他操作。
    猜你喜欢
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多