简体   繁体   English

从Node.js中的多部分请求检索JSON对象

[英]Retrieving JSON object from a multipart request in nodejs

var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
    if (err) {
        res.status(200).send('parsing error');
    }
});

var jsonObject;
var imageArray = [];

form.on('file', function(field, file) {
    console.log(file);
    if (file.type == 'application/json') {
        jsonObject = JSON.parse(fs.readFileSync(file.path, 'utf8'));
    } else if (file.type == 'image/jpeg') {
        imageArray.push(file.path);
    }
})

I'm using formidable to handle a multipart request in node.js made from my iOS app, the request usually contains "n" number of images and a associated JSON object, the formidable middleware treats the JSON as an file and stores the file in the temporary download location and provides a path to the file, the code "jsonObject = JSON.parse(fs.readFileSync(file.path, 'utf8'));" 我正在使用强壮的组件来处理我的iOS应用程序发出的node.js中的多部分请求,该请求通常包含“ n”张图片和一个关联的JSON对象,强大的中间件将JSON视为文件并将其存储在临时下载位置并提供文件的路径,代码为“ jsonObject = JSON.parse(fs.readFileSync(file.path,'utf8'));”; reads the file and parses into a JSON object. 读取文件并解析为JSON对象。 Is this how it is supposed to work or is there a better way, that negates the superfluous file write and read from the disk and provides a parsed JSON obj directly. 这是应该如何工作还是有更好的方法,它会否定从磁盘上进行多余文件的写入和读取,并直接提供已解析的JSON obj。

PS - newbie to node.js, heck newbie to entire backend system with a very bad case OCD. PS-Node.js的新手,非常糟糕的情况下,OCD可以使整个后端系统成为新手。

如果在Content-Disposition标头值中设置了文件filename (或者如果Content-Typeapplication/octet-stream则可能如此),强大(几乎所有其他节点形式的解析模块)将仅将特定部分视为文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM