通过POST和NSURLSession上传Image NSData [英] Uploading Image NSData via POST and NSURLSession

查看:119
本文介绍了通过POST和NSURLSession上传Image NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将单个UIImage上传到服务器,除了图像永远不会上传外,一切似乎都没问题。

I'm trying to upload a single UIImage to a server, and everything seems to be okay except that the image is never uploaded.

这是代码我用于在iOS上传图像:

This is the code I'm using to upload the image 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);
}];

服务器响应 200 OK状态并且没有错误,除了没有收到图像并且没有从服务器返回任何内容(如果没有上传图像,这是预期的。)

The server responds with a 200 OK status and no error, except the image is not received and nothing is returned from the server (this is expected if no image is uploaded).

这是服务器端代码:

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

正常请求(通过网络界面)记录以下内容:

A normal request (via the web interface) logs the following:

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

)

同时,从iOS发送的请求如下所示:

Meanwhile, the request sent from iOS looks as follows:

Array
(
)

对于我的生活,我无法弄清楚出了什么问题......有什么想法吗?

For the life of me, I can't figure out what's going wrong... Any ideas?

谢谢

推荐答案

问题出在 NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:...]

NSURLSessionUploadTask 忽略提供的请求体,并添加 fromData:参数作为请求体。但是,我只是提供图像数据,而不是格式正确的请求体...

NSURLSessionUploadTask ignores the request body provided and adds the fromData: parameter as the request body. However, I was just providing the image data and not the properly formatted request body...

固定代码是 NSURLSessionUploadTask * uploadTask = [ session uploadTaskWithRequest:来自data的请求:body completionHandler:...]

我会留下我的答案以防万一其他人偶然发现这个问题再次。

I'll leave my answer up in case anyone else stumbles across this problem again.

这篇关于通过POST和NSURLSession上传Image NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆