1

私の問題へのいくつかのリードを探しています。サーバーへの画像の投稿/アップロードに関連するすべてのリンクを実際に調べましたが、コードが機能していないようです。

私は2つのオプションを投稿しました...さまざまな方法で...コメントされたコードは...サーバーへのリクエストが空白になることを示しています。

別のオプションを使用してみました-appendPartWithFormData、appendPartWithFileData。

オプション1

NSError* エラー;

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

オプション 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];
4

2 に答える 2

0

これは通常私にとってはうまくいきます。RESTful スクリプトが正しいファイル ハンドルを取得するようにする必要があります。私はJavaを知りませんが、PHPでは次のようにします:$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];
于 2016-11-30T01:39:07.543 に答える