简体   繁体   中英

Upload an Image Using Objective C to a PHP Server

I'm developing an iphone app and using a POST request, I already read many post from this same topic but is still not working, I will appreciate some help, here is my code:

         //turning the image into a NSData object
         //getting the image back out of the UIImageView
         //setting the quality to 72

        NSData *image_data = UIImageJPEGRepresentation(picture, 72);

        // setting up the URL to post to
        NSMutableString *urlString = [[NSMutableString alloc] init];
        [urlString appendString:BASE_URL];
        [urlString appendString:@"mobile_services/mobile_store_services/upload_wishlist_image/"];
        //[urlString appendString:@"/temp_trash/temporal.php"];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [request setHTTPShouldHandleCookies:NO];
        [request setTimeoutInterval:30];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

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

        // file
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:image_data];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        // Text parameter1
        NSString *param1 = @"parameter text";
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"texto_prueba\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

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

        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        if(conn){
            web_data = [NSMutableData data];
        }else{
            NSLog(@"doesn't exist");
        }

I am using the NSURLConnectionDataDelegate protocol so, I received the data in this method:

    -(void) connectionDidFinishLoading:(NSURLConnection *)connection
    {
        //NSArray *json_data = [NSJSONSerialization JSONObjectWithData:web_data         options:kNilOptions error:NULL];
        NSString *returningString = [[NSString alloc] initWithData:web_data encoding:NSUTF8StringEncoding];
        NSLog(@"returned string = %@", returningString);

        [loadingView stopLoading];
    }

my PHP side, only tell me, what it received in this way:

    public function upload_wishlist_image()
    {

        var_dump($_REQUEST);

    }

Please some help!, PHP doesn't receive any image data.

It looks like you've given up on this technique and converted to base 64. I don't blame you, because creating these requests manually is cumbersome. In the future, if you use AFNetworking to make the request, life is much easier.

Anyway, if you're interested in why you code wasn't working, the first issue was the NSMutableURLRequest . It is very, very close, though a couple of observations:

  1. You should use the mime type of the file (in this case image/jpeg ) and only use application/octet-stream if you don't know the mime type of the file. So you should eliminate that application/octet-stream line.

  2. You should use \\r\\n at the end of each line, except the last one, before the binary data.

So, instead of:

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

You should have:

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

Second, once you fix the request, the PHP $_REQUEST variable should consist solely of the 'texto_prueba' => 'parameter text' . If you're not seeing that, then I'd question how you're doing that mapping from the URL to your PHP function.

But, in terms of the image you uploaded, you will not find that in $_REQUEST . The userfile parameter would be returned by $_FILES , not by $_REQUEST .

One other, final observation: You are converting your image back to a NSData via UIImageJPEGRepresentation . If you can grab the NSData (via dataWithContentsOfFile ) that is probably better than round-tripping it through a UIImage and back to a NSData , which will result in image degradation and loss of meta data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM