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!' });
});
});
這將是巨大的,如果我能得到我應該怎麼處理服務器端正確的建議。