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 回答
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];
于 2016-11-29T06:19:17.147 回答