通过POST和NSURLSession上传图像NSData

10
我正在尝试将一张UIImage上传到服务器,看起来一切都正常,但是这张图片从未被上传。这是我在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);
}];

服务器响应 200 状态码,没有错误,但没有收到图片并且服务器未返回任何内容(如果未上传图片,则此情况是预期的)。

这是服务端代码:

<?
    $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
            }
        }
    }
?>

一般的请求(通过Web界面)会记录以下信息:

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

)

与此同时,来自iOS的请求如下所示:

Array
(
)

我真的想不出到底出了什么问题... 有任何想法吗?

谢谢。

1个回答

16
问题出在NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:...]NSURLSessionUploadTask会忽略所提供的请求体,并将fromData:参数添加为请求体。然而,我只提供了图像数据,而没有正确格式化的请求体...
修复后的代码是 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:...]
我会保留我的回答,以防其他人再次遇到这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接