无法使用AFNetworking 3.0发送Multipart-Form数据

时间:2016-04-18 21:46:59

标签: ios objective-c node.js

目前,我尝试在Objective C中编写一个接受UIImage和NSString的方法,并向服务器发出POST请求。不幸的是,我无法发送任何东西。当我尝试使用HTML表单的表单时,我能够成功上传照片和参数。但是,我无法在我的iOS应用程序中复制它。当我尝试发出POST请求时,我一直收到404错误。

我已经尝试了两种不同的方法,根据其Github页面发送多表单数据POST请求,但没有成功。我在Xcode中调试了UIImage,我发现它确实存在。我认为它与我发送的参数有关。这些参数应该是formDataAppend的一部分,还是像我在下面那样的字典?

评论部分与其Github上的教程相对应。未注释的部分包含浏览Stackoverflow的部分仍无济于事。

+(void) uploadPhotoWithID:(NSString *)ownerID andPhotoImage:(UIImage *)image andCompletionHandler:(void (^)(MZPhoto *, NSError *))callback{

    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    NSDictionary *parameters = @{@"owner_id": ownerID};

//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:upload_photo_url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [formData appendPartWithFileData:imageData name:@"photo" fileName:@"temp.jpg" mimeType:@"image/jpeg"];
//    } error:nil];
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    
//    NSURLSessionUploadTask *uploadTask  = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        if(error){
//            NSLog(@"File Upload Failed");
//            
//        }
//        else{
//            NSLog(@" %@", responseObject);
//            MZPhoto *photo = [[MZPhoto alloc] initWithDictionary:responseObject error:nil];
//            callback(photo, nil);
//        }
//    }];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:upload_photo_url]];
    [manager POST:upload_photo_url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    } progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              NSLog(@" %@", responseObject);
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@" Failed");
          }];



}

这是我的Node.JS函数,

exports.upload_photo = function(req, res, next) {
    var owner_id = req.body.owner_id;
    console.log(owner_id);
    pg.connect(connectionString, function(err, client, done) {
        if (err) {
            done();
            console.log(err);
            return res.status(500).json({success: false, data: err});
        }

        var query = client.query("INSERT INTO photos (likes, dislikes, user_id) " +
                                    "VALUES (0, 0, $1) RETURNING photo_id, likes, dislikes, user_id", [owner_id]);
        var result;
        console.log(req.file);

        query.on('row', function(row) {
            row.file_url =  baseFileURL + row.photo_id + '.jpg';
            result = row;
        });

        query.on('end', function() {
            done();
            fs.rename('./static/photos/' + req.file.filename, './static/photos/' + result.photo_id + '.jpg', function(err) {
                if(err) console.log("Error Renaming the file!");
                return res.json(result);
            });
        });
    });
    console.log("Received photo upload from: " + owner_id);
}

1 个答案:

答案 0 :(得分:0)

尝试关注function

- (void) postServerRequest:(NSDictionary *)paramDict withData:(NSData*)fileData andType:(uploadType)uploadType Callback:(ResponseBlock) block{

    NSString * strServiceURL = @"Your Webservice URL";


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];


    [manager POST:strServiceURL parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (fileData!=nil){
            [formData appendPartWithFileData:fileData name:@"Key name on which you will upload file" fileName:@"Image name" mimeType:@"image/jpeg"];
        }

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        DLOG(@"Success: %@", responseObject);
        block(responseObject,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLOG(@"Error: %@", error);
        block (nil , error);
    }];
}