Marshall.Yang Marshall.Yang - 5 months ago 46
iOS Question

upload an image using AFNetworking to the server by node.js failed

I am learning AFNetworking(v3.0) these days, I try to use it to upload an image to my server writen by node.js + express. I found every time I tried to call upload method in ***.m I got error message, said the "Request failed: unacceptable content-type: text/html"(part of error message)", is that a problem maybe my request is wrong? Or the sever side's problem? I am new to node.js and express. What I guess is type problem? maybe but I don't know. If you know~ please reply me ~ thanks!

iOS Side:

NSDictionary *params = @{@"enctype": @"multipart/form-data"};

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://localhost:8080/images" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData *data = UIImagePNGRepresentation(self.imageView.image);
[formData appendPartWithFileData:data name:@"pic" fileName:@"pic.png" mimeType:@"image/png"];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"上传成功");
}
}];

[uploadTask resume];


Server Side:

router.route('/images').post(multiparty(), function(req, res) {
fs.readFile(req.files.image.path, function(err, data) {
var imageName = req.files.image.name;

if (!imageName) {
console.log("there was an error");
res.json({message:"error", code:500});
} else {
var newPath = __dirname + "/uploads/fullsize/" + imageName;
fs.writeFile(newPath, data, function(err) {
res.json({message: 'successfully upload image!', code:200});
});
}
});


});

Answer

Your iOS code is using pic as the field name, not image like you are referencing on the server side. One or the other would need to be changed.

Comments