Why does NSURLSession uploadTaskWithRequest:fromData: fail to upload to php server?

*爱你&永不变心* 提交于 2019-12-21 17:32:56

问题


The php code works fine. Ive uploaded files from a html form on the same server. The files uploaded ranged from 40K to 2.0M so its not size. File uploads is activated on the server running PHP 5.3

I found many posts such as this one (without an answer yet):https://stackoverflow.com/questions/19710388/using-nsurlsession-to-upload-an-image.

This one uses uploadTaskWithRequest:fromFile: instead of fromData:NSURLSession make sure Upload worked

This is NSURLSessionDataTask instead of uploadTaskWithRequest:No data receiving with NSURLSession

And some posts that seem to say uploadTaskWithRequest:fromData: simply doesn't work: NSURLSession: uploading assets with background transfer asynchronous upload with NSURLSession will not work but synchronous NSURLConnection does and Upload image from iOS to PHP

I have made the app such that it returns the HTTP code and I get code 200. The server error_log file has nothing in it after uploading. Everything seems to work fine but whatever happens, the file doesn't get written to the server. Any ideas what else I can try to find out whats going wrong?

Here is the php code:

<?php
$file='';
$uploaddir='';

////////////////
echo 'file count=', count($_FILES),"\n";
var_dump($_FILES);
echo "\n";
////////////////

if(isset($_FILES['userfile']['name'])){
      $uploaddir = './photos/'; //Uploading to same directory as PHP file
      $file = basename($_FILES['userfile']['name']);
      echo "file is set";
      $uploadFile = $file;
      $randomNumber = rand(0, 99999); 
      $newName = $uploaddir . $uploadFile;
        if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
            echo "Temp file uploaded. \r\n";
        } else {
            echo "Temp file not uploaded. \r\n";
        }
   if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) {
         $postsize = ini_get('post_max_size'); //Not necessary, I was using these
         $canupload = ini_get('file_uploads'); //server variables to see what was 
         $tempdir = ini_get('upload_tmp_dir'); //going wrong.
         $maxsize = ini_get('upload_max_filesize');
         echo "\r\n" .  $_FILES['userfile']['size'] . "\r\n" . $_FILES['userfile']['type'] ;
    }
}
?>

and here is the iOS code:

- (void)uploadImage:(UIImage*)image {

    // 0 Define URL
    NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myserver.com/app/photos/uploadPhoto.php"]];
    NSString *boundary = @"0xKhTmLbOuNdArY";
    NSString *filename = [NSString stringWithFormat:@"someName.jpg"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

    // 4 Create object to put content into...
    NSMutableData *body = [NSMutableData data];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\" filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
    //[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    //Not used with this:https://stackoverflow.com/questions/20893171/asynchronous-upload-with-nsurlsession-will-not-work-but-synchronous-nsurlconnect/20896632?noredirect=1#comment39074802_20896632
    //[request setHTTPBody:body];


    __block NSString *stringForText = @"Hola";
    ///////////////////////////////////////////////////
    // 3
    self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // ...
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
        int errorCode = httpResponse.statusCode;
        NSString *errorStatus = [NSString stringWithFormat:@"%d",errorCode];

        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSString *totalResponse = [errorStatus stringByAppendingString:responseString];

        stringForText = totalResponse;
        [self updateView:stringForText];
        //UIAlertView *alertme = [[UIAlertView alloc] initWithTitle:@"error" message:totalResponse delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        //[alertme show];
        // 4
        self.uploadView.hidden = NO;
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    }];


    // 5
    [_uploadTask resume];
}

-(void)updateView:(NSString*)texto{
    dispatch_sync(dispatch_get_main_queue(), ^{
        self.myTextView.text = texto;
    });

}

I have 777 permissions on that folder. As I said, Ive been able to upload and thus write to that folder from the same php script via an html form.

The totalResponse is 200 for the http error code and count=0 as well as array(0) {} for the php dump.

Here is the image of the response from the server right in the app:

I added these lines after echoing Temp file uploaded:

$body = $HTTP_RAW_POST_DATA;
echo "\n REQUEST" . $body;

But I only got this:

file count=1 array(1) { ["user file"]=> array(5) { ["name"]=> string(12) "DrinkCO2.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(14) "/tmp/phpxg7oLZ" ["error"]=> int(0) ["size"]=> int(190550) } } file is setTemp file uploaded. REQUEST 190550 image/png

回答1:


It wasn't missing a colon, it was missing a semi-colon.

"name=\"userfile\" : filename=\"%@\"\r\n""

Should be

"name=\"userfile\"; filename=\"%@\"\r\n""

At least this is the only way your code worked for me (thanks by the way!).




回答2:


I had an issue with a semi-colon here->

"name=\"userfile\" ; filename=\"%@\"\r\n"" 

So it was a malformed body basically.



来源:https://stackoverflow.com/questions/25127058/why-does-nsurlsession-uploadtaskwithrequestfromdata-fail-to-upload-to-php-serv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!