0
我尝试将图像提交到我的服务器。使用Mongoose将多个图像上传到Node.js服务器
在Objective-C部分,我使用带有“name”和“filename”的“form-data”将图像数据附加到HTTP正文。以下是相关的片段。我很确定其他部分应该是正确的。请专注符合“内容处置”如果必要的话:
...
// Append image data to body data
NSMutableData *bodyData = [NSMutableData data];
int i = 1;
for (NSData *imgData in allImgData) {
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photoToUpload[]\"; filename=\"%@%d.png\"\r\n", fileParamConstant, i] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:imgData];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
i++;
}
// Append one last boundary
[bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:bodyData];
...
问题
然而,在网上搜索几个职位后,我还不太确定,我应该如何处理服务器部分与nodejs使用猫鼬。基于我的Objective-C部分,我应该从“req.body”还是“req.files”获取图像?所以我认为我的问题也在于了解HTTP请求,特别是与上面的“Content-Disposition”部分有关。
下面是我当前的代码的NodeJS:
// on routes that end in /users/competitorAnalysisPhotoData
// ----------------------------------------------------
router.route('/users/competitorAnalysisPhotoData/:userName')
// update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisPhotoData)
.put(function(req, res) {
// use our user model to find the user we want
User.findOne({ userName: req.params.userName}, function(err, user) {
if (err)
res.send(err);
console.log('Got the user in "Put"!');
// update the photos -- Version 1
user.competitorAnalysis.push({
photo1: req.body.photo1,
photo2: req.body.photo2,
photo3: req.body.photo3,
photo4: req.body.photo4
});
console.log('req.body.photo1: %s', req.body.photo1);
console.log('Save the photo data for competitorAnalysisPhotoData!');
// update the photos -- Version 2
user.competitorAnalysis.photo1.data = fs.readFileSync(req.files.photo1.path)
user.competitorAnalysis.photo1.contentType = 'image/png';
user.competitorAnalysis.photo2.data = fs.readFileSync(req.files.photo2.path)
user.competitorAnalysis.photo2.contentType = 'image/png';
user.competitorAnalysis.photo3.data = fs.readFileSync(req.files.photo3.path)
user.competitorAnalysis.photo3.contentType = 'image/png';
user.competitorAnalysis.photo4.data = fs.readFileSync(req.files.photo4.path)
user.competitorAnalysis.photo4.contentType = 'image/png';
console.log('req.files.photo1.path: %s', req.files.photo1.path);
console.log('Save the photo data for competitorAnalysisPhotoData!');
// save the user
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'User updated!' });
});
});
这将是巨大的,如果我能得到我应该怎么处理服务器端正确的建议。