加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – NSURLSessionUploadTask无法上传文件

发布时间:2020-12-13 17:56:37 所属栏目:PHP教程 来源:网络整理
导读:下面是上传图像文件的片段.我只想使用NSURLSessionUploadTask,因为它提供了我想在我的应用中使用的后台上传功能. 另外我想POST参数和文件上传. 我也不擅长服务器端代码.任何人都可以指导我做错了什么. 上传代码 NSString* filePath = [[NSBundle mainBundle]
下面是上传图像文件的片段.我只想使用NSURLSessionUploadTask,因为它提供了我想在我的应用中使用的后台上传功能.

另外我想POST参数和文件上传.

我也不擅长服务器端代码.任何人都可以指导我做错了什么.

上传代码

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];
uint64_t bytesTotalForThisFile = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileSize];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadPath];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%llu",bytesTotalForThisFile] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];

[request setTimeoutInterval:30];

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];


NSURLSessionUploadTask *taskUpload= [self.uploadSession uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:filePath]];

PHP代码

<?php

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"],$strPath ) ) {
    print "The file " .  $strPath . " has been uploaded.";
} else {
    print "There was an error uploading the file,please try again!";
}

从服务器端我得到$_FILES的空数组

我将举一个代码示例.检查控制台是否出现任何错误.
// 1. config
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

// 2. if necessary set your Authorization HTTP (example api)
// [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}];

// 3. Finally,you create the NSURLSession using the above configuration.
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// 4. Set your Request URL
NSURL *url = <yourURL>;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

// 5. Set your HTTPMethod POST or PUT
[request setHTTPMethod:@"PUT"];

// 6. Encapsulate your file (supposse an image)
UIImage *image = [UIImage imageNamed:@"imageName"];
NSData *imageData = UIImageJPEGRepresentation(image,1.0);

// 7. You could try use uploadTaskWithRequest fromData
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    if (!error && httpResp.statusCode == 200) {

        // Uploaded

    } else {

       // alert for error saving / updating note
       NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld",error,(long)httpResp.statusCode);
      }
}];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读