2016-08-31 37 views
2

AFNetworking 3.0でサーバーにイメージをアップロードしようとしています。画像アップロードでエラー:イメージAFNetworking 3.0でアップロードする

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
    [[manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) 
    { 
     //Current date with image name 
     NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"]; 
     [formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"]; 
     }progress:nil 
     success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) 
     { 
      NSLog(@"%@",responseObject); 
      [GMDCircleLoader hideFromView:self.view animated:YES]; 
      NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject]; 
      if([dir valueForKey:@"error"]) 
      { 
       UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ]; 
       [self.parentViewController presentViewController:alert animated:YES completion:nil]; 
      } 
      else 
      { 
       //Successfull 
       UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert]; 
       UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) 
       { 
        [self.navigationController popViewControllerAnimated:YES]; 
       }]; 
      [alertController addAction:ok]; 
      [self presentViewController:alertController animated:YES completion:nil]; 
      } 
      NSLog(@"response object : %@",responseObject); 
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {      NSLog(@"failure : %@",error.localizedDescription); 
    }]resume]; 


それはエラーで成功ブロックになります:

は、ここに私のコードです。
私はまた、私のAPIレスポンスをチェックするためにPostmanから試しましたが、Postmanからうまくいっています。このコードの問題は何ですか?

+1

ファイルをbase64またはシンプルファイルとして受け入れる – gurmandeep

+0

レスポンスを表示しますか? –

+0

はい。それはいいよ – gurmandeep

答えて

0

あなたは

これは、あなたがマルチパート/ "あなたは@にrequestSerializerを設定する必要がenter image description here

+0

私はmanager.responseSerializerで試しています。 acceptableContentTypes = [NSSet setWithObject:@ "application/json"];しかしそれはまだ高揚していない。 BSMachError:(os/kern)無効な機能(20) _BSMachError:(os/kern)無効な名前(15) –

+0

http://stackoverflow.com/questions/32899586/error-message-bsmacherror- os-kern-invalid-capability-20 – vaibby

0
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:imageBytes options:0]; 
NSMutableDictionary *parameters = [NSMutableDictionary dictionary]; 

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];// Your API 

    [manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
    { 
     //do not put image inside parameters dictionary as I did, but append it! 
     [formData appendPartWithFileData:nsdataFromBase64String name:fIds fileName:fileN mimeType:@"image/jpeg"]; 

    } 
    success:^(NSURLSessionDataTask *task, id responseObject) 
    { 
     [email protected]"success"; 
     //here is place for code executed in success case 
    } 
    failure:^(NSURLSessionDataTask *task, NSError *error) 
    { 
     [email protected]"fail"; 
     //here is place for code executed in error case 
    }]; 

作品を試してみてください@ "Content-Type"のための "form-data"です。

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
    manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 


    manager.responseSerializer=[AFJSONResponseSerializer serializer]; 

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"]; 
    [manager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"]; 


    [manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { 
     NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"]; 
     [formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"]; 


    } progress:^(NSProgress * _Nonnull uploadProgress) { 

    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 

     NSLog(@"%@",responseObject); 
      [GMDCircleLoader hideFromView:self.view animated:YES]; 
      NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject]; 
      if([dir valueForKey:@"error"]) 
      { 
       UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ]; 
       [self.parentViewController presentViewController:alert animated:YES completion:nil]; 
      } 
      else 
      { 
       //Successfull 
       UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert]; 
       UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) 
       { 
        [self.navigationController popViewControllerAnimated:YES]; 
       }]; 
      [alertController addAction:ok]; 
      [self presentViewController:alertController animated:YES completion:nil]; 
      } 
      NSLog(@"response object : %@",responseObject); 
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 
     NSLog(@"error: %@", error.localizedDescription); 

    }]; 
+0

imageBytesはnsdataですか? –

+0

はい、まずサーバーからimageBytesを取得します。そしてNSDataに戻して画像をサーバに戻すように変更します – gurmandeep

+0

私は理由があります: '無効なパラメータが満たされていません:本体 –

0

ポストマン で使用しているものである私の最後で完全にこの

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"]; 
+1

まだそれは行われていませんエラー: "画像のアップロードでエラーが発生しました"; –

+0

Share this postmanそれ以外のコード – gurmandeep

0
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:"your image as base64 encoded" options:0]; 

NSDictionary *parameters = [NSMutableDictionary dictionary]; 

parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"wr34", @"delivery_company_name", @"uname", @"user_name", @"123456789", @"contact_info", @"[email protected]", @"email",@"123456", @"password",@"SUV", @"car_type",@"White", @"car_color",@"GJ-1AE-2255", @"car_plate_no",@"43345dw", @"car_reg_no",@"123454", @"license_no",@"Model", @"car_model",@"location", @"location",@"4.3", @"latitude",@"8.7", @"longitude",@"notes", @"deliver_terms_conditions",@"notes", @"notes", nil]; 

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]]; 
manager.responseSerializer = [AFJSONResponseSerializer serializer]; 
manager.requestSerializer = [AFJSONRequestSerializer serializer]; 

[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{ 
    //do not put image inside parameters dictionary as I did, but append it! 
    [formData appendPartWithFileData:nsdataFromBase64String name:@"ToyotaSupra" fileName:@"ToyotaSupra" mimeType:@"image/png"]; 

} 
     success:^(NSURLSessionDataTask *task, id responseObject) 
{ 
    [email protected]"success"; 
    //here is place for code executed in success case 
} 
     failure:^(NSURLSessionDataTask *task, NSError *error) 
{ 
    [email protected]"fail"; 
    //here is place for code executed in error case 
}]; 

コードの下に試してみて、それがAFNetworking 3.0での作業

https://www.dropbox.com/s/3ot6kpiqs3pn2h0/AFNetwork.zip?dl=0

+0

あなたが使用したafnetworkingのバージョンは? –

+0

作業中3.0 – gurmandeep

+0

[manager POST:stringURL parameters :パラメータconstructingBodyWithBlock:^(id formData)はあなたのコードから非難されています前回と同じコードを試していますが、この推奨されていない警告の後に動作していません –

1

作業コードをダウンロードしてください:あなたがAPIをする郵便配達のスクリーンショットを追加してくださいすることができ

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



    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments]; 


    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:BaseURL parameters:<parameter dictionary> constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
            { 

             if (profile_pic.length!=0) { 

              [formData appendPartWithFileData:imageData name:@"profile_pic" fileName:@"ProfilePic" mimeType:@"image/jpeg"]; 
             } 


            } error:nil]; 

    NSURLSessionUploadTask *uploadTask; 
    uploadTask = [manager 
        uploadTaskWithStreamedRequest:request 
        progress:^(NSProgress * _Nonnull uploadProgress) { 
         // This is not called back on the main queue. 
         // You are responsible for dispatching to the main queue for UI updates 

        } 
        completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
         if (error) 
         { 


         } 
         else 
         { 

         } 
        }]; 

    [uploadTask resume]; 
+0

を送った私は応答を得た成功した。サーバーでは、私が見つけられなかったイメージ名は、すなわち、profilepic –

+0

あなたのパラメータ名(名前:@ "profile_pic")が正しいことを確認します –

+0

私はそのパラメータに従います。私の元のパラメータではうまくいかないのですが、あなたのパラメータではうまくいきました。サーバーでイメージ名を表示しません。 –

関連する問題