使用node.js使用afnetworking将图像上传到服务器上



我如今正在学习afnetworking(v3.0),我尝试使用它将图像上传到由node.js express撰写的服务器上。我发现每次尝试在***中调用上传方法。m我收到错误消息,说"请求失败:不可接受的内容类型:text/html"(错误消息的一部分)",是一个问题,这是我的问题。请求是错误的吗?还是Sever Side的问题?我是Node.js的新手。

ios方面:

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];

服务器端:

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});
        });
    }
});

});

您的iOS代码将pic用作字段名称,而不是您在服务器端引用的image。一个或另一个需要更改。

最新更新