dongyimo1293 2014-04-23 19:55
浏览 88

使用AFNetworking上传图像选择器

Sorry for my ignorance. I can't quite get a hang of it all yet.

So currently I have the code:

NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL
                                                 URLWithString:@"http://xyz.co.uk/zyx/imageupload.php"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"image/png"
   forHTTPHeaderField:@"Content-type"];
    [request setValue:[NSString stringWithFormat:@"%lu",
                       (unsigned long)[imageData length]]
   forHTTPHeaderField:@"Content-length"];
     [request setHTTPBody:[self imageDataToSend]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

imageupload.php:

<?php
$handle = fopen("image.png", "wb"); // write binary

fwrite($handle, $HTTP_RAW_POST_DATA);

fclose($handle);

print "Received image file.";
?>

Which uploads a photo to my website... Perfect... NO!

I have noticed some problems.

  1. There is no loading gif at the top of the iphone indicating any kind of activity.
  2. There is no way to create a delegate sector so that I can indicate if there has been an error or success.

I then looked towards this. Which was all well and good until I realised that it infact was rubbish and I have received a million errors on trying to upload it. Also everyone told me that I am going in the wrong direction "ASIHTTPRequest is old. You should use AFNetworking".

And I am now trying to work with AFNetworking but it is proving to be extremely difficult! I can't see how it is similar to ASIHTTPRequest at all.


Can anybody help me do the equivelant kind of thing with AFNetwork. Or a whole knew way of uploading image data to my php file.


Errors from Jai Govindani:

enter image description here

  • 写回答

1条回答 默认 最新

  • dougao1106 2014-04-23 20:25
    关注

    Here's an example of photo upload using AFNetworking - ZodioAPIClient is my AFHTTPClient subclass. You'll want to subclass AFHTTPClient (and usually create a singleton to do stuff like below). The filenames are of course your choice, all that really matters is appending the NSData. Note that this is for AFNetworking < 2.0. 2.0's structure is different but if you can understand below, you can migrate it to 2.0 pretty easily.

    The steps are (this applies to all AFNetworking operations, with some special steps for the photo data):

    1. Create an NSMutableURLRequest and append the NSData
    2. Create an AFJSONRequestOperation using the NSMutableURLRequest and specify your success/failure blocks
    3. optional - specify an upload progress block with a callback to whoever/whatever you want to use to handle upload progress
    4. Enqueue the operation (if you don't do this nothing will happen, the operation won't get started)

    NSData *photo = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
    
    NSMutableURLRequest *addPhotoRequest = [[YourAFHTTPClientSubclass sharedClient] multipartFormRequestWithMethod:@"POST" path:addPhotoPath parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
                               {
                                   [formData appendPartWithFileData:photo name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
                               }];
    
    AFJSONRequestOperation *addPhotoRequestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:addPhotoRequest
                                                                                                    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    
                                                     {
                                                         DDLogVerbose(@"in add photo success block");
                                                     }
                                                      failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                                     {
                                                         DDLogVerbose(@"request that errored: %@", request);
                                                         DDLogVerbose(@"Request failed with error: %@, %@", error, error.userInfo);
                                                         DDLogVerbose(@"the response I got was: %@", JSON);
                                                     }];
    
    [addPhotoRequestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
     {
         DDLogVerbose(@"Total progress: %f", (totalBytesWritten * 1.0f)/(totalBytesExpectedToWrite * 1.0f));
     }];
    
    [[YourAFHTTPClientSubclass sharedClient] enqueueHTTPRequestOperation:addPhotoRequestOperation];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化