我试图找到这个问题的解决方案,在node.js / express.js和iOS app中找不到任何东西。我的客户有要求不使用任何第三方库。所以,我没有使用AFNetworking。任何帮助,或者如果有人能够告诉我们为什么会出现错误,将会非常感激。
我正在尝试发送多部分表单数据,带有文本的图像。每当我做POST时,我都会得到错误:多部分数据的意外结束。
iOS中的POST代码:
NSURL *url = [NSURL URLWithString:@"http://172.16.0.5:8080/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"YOUR_BOUNDARY_STRING";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"%@.jpg\"\r\n", self.path] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:self.imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n%@", self.mealTitleTextField.text] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"user\"\r\n\r\n%d", 1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
这就是我获取图像文件路径的方式:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.path = [documentsDirectory stringByAppendingPathComponent:
@"test.png" ];
self.imageData = UIImagePNGRepresentation(image);
[self.imageData writeToFile:self.path atomically:YES];
这是服务器代码:
router.post('/upload', function(req,res,next){
upload.single('photo')(req, res, function(err){
if (err) {
console.log(err)
res.send(err);
return;
}
console.log(req.file);
res.json({'ok':'ok'});
});
});``
答案 0 :(得分:0)
您应该验证上传的表单数据的格式 - 可能缺少一些LINE_END或LINE_START,请参阅cordova-plugin-file-transfer Android implementation作为参考。
答案 1 :(得分:0)
就我而言,我安装了https bypass
应用。
当我关闭应用程序时,错误消失了。