Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何定义最大上载文件大小&;NodeJs restify bodyParser中允许的文件类型?_Node.js_Restify - Fatal编程技术网

Node.js 如何定义最大上载文件大小&;NodeJs restify bodyParser中允许的文件类型?

Node.js 如何定义最大上载文件大小&;NodeJs restify bodyParser中允许的文件类型?,node.js,restify,Node.js,Restify,我是node.js的新手。我已经使用Restify模块将图像文件上传到Rest服务器。但现在,我需要确保我上传的图像文件大小和bodyParser中允许的文件类型能够恢复 我的restify代码是: var restify = require('restify'), fsEx = require('fs-extra'), md5 = require("md5"), path = require("path"); var server = restify.createSe

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

我的restify代码是:

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();
});
const maximumImageSize=1*1024*1024;
const allowedImageFormats=['.png'、'.jpg'、'.jpeg'];
const isValidImageFormat=(扩展)=>(允许的图像格式,.toLower(扩展));
常量isValidImageSize=(大小)=>size
好主意,但是
内容长度
不是图像大小,而是正文大小。正确。此代码来自一个项目,其中端点只上载了一个图像,因此在本例中它可以工作。但是你是对的,如果身体包含的不仅仅是一个图像,那么就需要做其他的事情。
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.'));
}