无法使用AFMultipartFormData将图像发布到服务器

时间:2015-04-23 19:23:43

标签: ios afnetworking afnetworking-2

我在将图片上传到服务器时遇到问题。我回答了类似的问题,但我似乎无法找到解决方案。

服务器需要一个带有@“avatar”的图像文件作为密钥。

这是我创建图像数据的方式

NSData *imageData = UIImageJPEGRepresentation(info[UIImagePickerControllerEditedImage], 1.0);
    if (imageData != nil)
    {
        [[restClient sharedInstance]updateAvatarWithData:imageData andIfSuccess:^(NSDictionary *dict) {
            if (dict)
            {
                NSLog(@"dict %@",dict);
            }
        } orIfFail:^(NSError *err) {
            if (err)
            {
                NSLog(@"error %@",err);
            }
        }];
    }

//将其发送到服务器 // restClient.m

- (void)updateAvatarWithData:(NSData *)imageData andIfSuccess:(void (^)(NSDictionary *))successBlock orIfFail:(void (^)(NSError *))failureBlock
{
    AFHTTPRequestOperationManager *manager  = [[restClient sharedInstance] requestManager];
    NSString *url                           = [NSString stringWithFormat:@"%@/somePath", BASEURL];

    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
    if (successBlock)
    {
    successBlock(responseObject);
    }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    if (failureBlock)
    {
    failureBlock(error);
    }
    }];

这是我得到的回应

lldb) po [operation responseString]
{"message":"Validation Failed","errors":[{"resource":"User","field":"avatar","code":null}]}

(lldb) po error
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: client error (422)" UserInfo=0x1702f0c80 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17443aa0> { URL: url } { status code: 422, headers {
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "no-cache";
"Content-Type" = "application/json; charset=utf-8";
"Set-Cookie" = "request_method=POST; path=/; secure, XSRF-TOKEN=gMHgjVq7F7fUwoDChpWH0mAwnDxkfGxPg8RzdKdk1g%3D%3D; path=/; secure,; path=/; secure; HttpOnly";
Status = "422 Unprocessable Entity";
"Strict-Transport-Security" = "max-age=315";
"access-control-allow-credentials" = true;
com.alamofire.serialization.response.error.data=<>, NSLocalizedDescription=Request failed: client error (422)}

感谢任何帮助

0 个答案:

没有答案
相关问题