Mit dem hochladen von NSData per POST und NSURLSession

Ich versuche das hochladen einer einzelnen UIImage auf einen server, und alles scheint in Ordnung zu sein, außer, dass das Bild nie hochgeladen.

Dies ist der code, den ich verwende, um das Bild hochzuladen in iOS:

const NSString *boundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
const NSString *fileParamConstant = @"photo";

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryConstant];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:info[UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
    ALAssetRepresentation *representation = [asset defaultRepresentation];

    //get byte size of image
    long long size = [representation size];
    unsigned char *bytes = malloc(size);

    //read image data into bytes array
    [representation getBytes:bytes fromOffset:0 length:size error:nil];

    NSData *imageData = [NSData dataWithBytesNoCopy:bytes length:size freeWhenDone:YES];

    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParamConstant, filename] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n",[SWNetworkController contentTypeForImageData:imageData]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *postLength = [NSString stringWithFormat:@"%zu", [body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setHTTPBody:body];

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"STRING %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@", response);
        NSLog(@"%@", error);
    }];
    [uploadTask resume];
} failureBlock:^(NSError *error) {
    NSLog(@"Image error:\n%@",error);
}];

Antwortet der server mit einem 200 status OK und keine Fehler, außer das Bild ist nicht erhalten, und nichts wird vom server zurückgegeben (dies wird erwartet, wenn kein Bild hochgeladen wird).

Hier ist der server-seitige code:

<?
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["photo"]["name"]);
    $extension = end($temp);

    error_log(print_r($_FILES, true));

    if ((($_FILES["photo"]["type"] == "image/gif")
    || ($_FILES["photo"]["type"] == "image/jpeg")
    || ($_FILES["photo"]["type"] == "image/jpg")
    || ($_FILES["photo"]["type"] == "image/pjpeg")
    || ($_FILES["photo"]["type"] == "image/x-png")
    || ($_FILES["photo"]["type"] == "image/png"))
    && ($_FILES["photo"]["size"] < 20000000)
    && in_array($extension, $allowedExts)) {
      if ($_FILES["photo"]["error"] == 0) {
        $filename = sha1($_FILES['photo']['name'] . uniqid("",true));
            if (move_uploaded_file($_FILES['photo']['tmp_name'], 'pic/' . $filename . "." . $extension)) {
                //do stuff with the saved image here
            }
        }
    }
?>

Einer normalen Anfrage (via web-interface) protokolliert die folgenden:

Array
(
    [photo] => Array
    (
        [name] => BoPzSyRIgAAe1h6.jpg-large.jpeg
        [type] => image/jpeg
        [tmp_name] => /var/tmp/phpjScXQB
        [error] => 0
        [size] => 67900
    )

)

Mittlerweile die Anforderung gesendet von iOS sieht wie folgt aus:

Array
(
)

Für das Leben von mir, ich kann nicht herausfinden, was falsch läuft... Irgendwelche Ideen?

Dank

InformationsquelleAutor jaggedcow | 2014-05-27
Schreibe einen Kommentar