我尝试将图片提交到我的服务器。
在Objective-C部分,我使用" form-data"将图像数据附加到HTTP主体。与"名称"和"文件名"。以下是相关片段。我非常确定其他部分应该是正确的。请关注" Content-Disposition"如有必要:
...
// 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];
...
问题
但是,在网上搜索了几个帖子后,我仍然不太确定如何使用mongoose 处理带有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!' });
});
});
如果我能就如何正确处理服务器端获得一些建议,那就太棒了。
答案 0 :(得分:1)
使用GridFS或本地文件系统存储文件,然后在您的mongoose模型中引用该文件。如果您知道图像/文件的大小是安全的(远低于16MB +模型的其余部分),您可以将其存储为模型中的Blob(ByteArray)。