微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 通过POST和NSURLSession上传Image NSData

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

这是我用来在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状态响应并且没有错误,除了没有接收到图像并且没有从服务器返回任何内容(如果没有上载图像,这是预期的).

这是服务器端代码

<?
    $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
(
)

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

谢谢

解决方法

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

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

固定代码是NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:…]

我会留下我的答案,以防其他人再次遇到这个问题.

原文地址:https://www.jb51.cc/iOS/334562.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐