2016-11-28 7 views
1

私は私の問題のいくつかのリードを探しています。 イメージをサーバーに投稿/アップロードすることに関連するすべてのリンクを実際に見てきましたが、私のコードを動作させるものは何もありません。パラメータを使用した画像の投稿 - AFNetworking 3.1および目的c(Xcode 8)

私は2つのオプションを...異なる方法で投稿しました...コメント付きコードは、そのことを示しています...私のリクエストはサーバーに空白になります。

私はさまざまなオプション、appendPartWithFormData、appendPartWithFileDataを試してみました。

オプション1

NSError * error;

// Create paths to output images 
    NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"]; 
    UIImage *image = [UIImage imageWithData:self.imageData]; 
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES]; 
    NSURL *imagePath = [NSURL fileURLWithPath:pngPath]; 

    NSData *jsonInputData  = [NSJSONSerialization dataWithJSONObject:[requestParameter valueForKey:@"Param"] options:0 error:&error]; 
    NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding]; 

    NSLog(@"converted JOSN Data %@",jsonInputString); 

    NSDictionary* params = @{@"request": jsonInputString }; 

    [manager POST:[requestParameter valueForKey:@"methodName"] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
    { 
     //[formData appendPartWithFormData:self.imageData name:@"profilepic" ]; 

     //[formData appendPartWithFileData:self.imageData name:@"profilepic" fileName:@"profilepic.png" mimeType:@"image/png"]; 
     [formData appendPartWithFormData:jsonInputData name:@"request"]; 
     [formData appendPartWithFileURL:[NSURL fileURLWithPath:pngPath] 
            name:@"File" 
            error:nil]; 
    } progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { 
     NSLog(@"Success: %@", responseObject); 
     [self requestSuccessed:responseObject]; 

    } failure:^(NSURLSessionDataTask *task, NSError *error) { 

     NSLog(@"Error: %@", error); 
     [self requestFailed:error]; 
    }]; 

OPTION 2

NSError* error; 

    NSData *jsonInputData  = [NSJSONSerialization dataWithJSONObject:[requestParameter valueForKey:@"Param"] options:0 error:&error]; 
    NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding]; 
    NSDictionary* params = @{@"request": jsonInputString }; 

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

    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@“XXXXXXX”] parameters:nil error:nil]; 


    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue]; 
    // [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    // [req setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSMutableData *body = [NSMutableData data]; 
    NSString *boundary = @"---------------------------14737809831466499882746641449"; 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"pic.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:self.imageData]; 
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [req addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"request\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:jsonInputString] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

    // close form 
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [req setHTTPBody:body]; 

    [[manager1 dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 

     if (!error) { 
      NSLog(@"Reply JSON: %@", responseObject); 

      if ([responseObject isKindOfClass:[NSDictionary class]]) { 
       //blah blah 
      } 
     } else { 
      NSLog(@"Error: %@, %@, %@", error, response, responseObject); 
     } 
    }] resume]; 
+0

ポストコールに送信し、実際にファイルを保存します。最終的に何らかの形の資格認定を使用しています。 – Alex

+0

ありがとうアレックス..サーバはJavaで実装されていて、Postmanpluginから同じリクエストを投稿すると、formdataにpngファイルが添付されています - 要求はうまく行き、正常な応答が得られます。 – Vijaya

答えて

0

は、これは通常、私の作品

 // your parametes here 
    userInfoDict=[[NSMutableDictionary alloc] init]; 

    [userInfoDict setValue:@"image" forKey:@"iamge"]; 

    // if image is too large than the timeout intervel 
// [_request setTimeoutInterval:1000]; 

    _request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"api url" parameters:userInfoDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
       { 
       //convert imahe into data 
        NSData* data = UIImagePNGRepresentation(yourImage); 

        [formData appendPartWithFileData:data name:@"api paramets name in which you want to post image" fileName:@"myImage.png" mimeType:@"image/png"]; 

       } error:nil]; 

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

    _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 
         dispatch_async(dispatch_get_main_queue(), ^{ 
          //Update the progress view 
          [_playerProgress setProgress:uploadProgress.fractionCompleted]; 

          NSLog(@"\n uploading image vlaues %f\n",uploadProgress.fractionCompleted); 

          // for uploading video in background 
          manager.attemptsToRecreateUploadTasksForBackgroundSessions=YES; 

         }); 
        } 

        completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
         if (error) { 
          NSLog(@"Error: %@", error); 

          // [_playerProgress setHidden:YES]; 

         } else 
         { 
          NSLog(@"%@ ", response); 

          // after upload comnlete disablle background uploading 

          manager.attemptsToRecreateUploadTasksForBackgroundSessions=NO; 

          NSLog(@"\n\n REsponse Form Server %@\n\n",responseObject); 
          //[responseObject valueForKey:@"error"]; 
                  //remove temp file 
          NSError *error; 

         } 
        } 

        ]; 

    [_uploadTask resume]; 
+0

ありがとうございましたNouman ...あなたのソリューションを試しましたが、役に立たなかった...リクエストは空白になります – Vijaya

+0

@Vijayaこれを試してみてください。 –

+0

ありがとうもう一度Nouman ... jpegからpngに変更すると、私は早くも試しましたが、私はまだあなたのコードを先に進めました。私は何か他のものを見逃しているかもしれません。 – Vijaya

0

うまくいけば、それはあなたの問題を解決する、これを試してみてください。 RESTfulなスクリプトが正しいファイルハンドルを受け取るようにする必要があります。私は、Javaを知らない、しかしとしてPHPで私はそれを行うだろう:私はあなたが聞くために、サーバー側でのREST APIのいくつかのフォーム(PHP、Perlの、のNode.jsなど)が必要になると思う$image = $_FILES["imagename"]["name"];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    NSLog(@"Saving image file"); 

    [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:@"imagename" fileName:@"image.png" mimeType:@"image/png"]; 

} error:nil]; 

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

NSURLSessionUploadTask *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 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSLog(@"JSON uploadProgress.fractionCompleted: %f", uploadProgress.fractionCompleted); 
    }); 
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 

    //NSLog(@"Error: %@", error); 
    NSLog(@"RESPONSE: %@ %@", response, responseObject); 
    if(error) { 
     NSLog(@"Error: %@", error); 

    } else { 
     NSString *responseString = [[[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding] mutableCopy]; 
     NSLog(@"RESPONSE: %@", responseString); 
    } 
}]; 
[uploadTask resume]; 
+0

ありがとうアレックス...これは私のために働かなかったどちらか...私はサーバー上で多くのアイデアはありませんが、アンドロイドのアプリケーションバイト配列から画像のために送信され、サーバーはそれを拾う。 .. – Vijaya

関連する問題