首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSURLSessionUploadTask上传文件失败

NSURLSessionUploadTask上传文件失败
EN

Stack Overflow用户
提问于 2015-06-30 06:03:46
回答 2查看 732关注 0票数 7

下面是上传图像文件的片段,我只想使用NSURLSessionUploadTask,因为它提供了后台上传功能,我想在我的应用程序中使用。

另外,我想在上传文件的同时发布参数。

另外,我在服务器端code.Can不好,任何人都请指点我做错了什么。

上传代码

代码语言:javascript
复制
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代码

代码语言:javascript
复制
<?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的空数组

EN

回答 2

Stack Overflow用户

发布于 2015-07-07 18:39:14

我将举一个代码的例子。检查控制台上是否有任何错误。

代码语言:javascript
复制
// 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);
      }
}];
票数 0
EN

Stack Overflow用户

发布于 2016-05-01 05:19:33

如果这是完整的代码,那么您实际上并不是启动上传。NSURLSession任务不会自动启动(与某些NSURLConnection调用不同)。你必须显式地调用他们的简历方法来开始上传,否则任务就会坐在那里什么也不做。

其次,您应该真正使用URLForResource,而不是使用路径,然后将其转换为URL。这不应该破坏您的代码,但它是一个更干净的只是使用URL开始。

第三,如果您确实需要使用路径,那么方便方法(fileURLWithPath:)是您的朋友。

第四,您不需要设置内容长度,而IIRC则可能不需要设置内容长度,因为如果NSURLSession协商任何类型的编码(例如压缩文件数据),您不知道内容长度实际上是多少。

第五,如果文件很大,30秒可能不够长。

第六,如果您在较新版本的iOS或OS上运行,请确保您使用的是配置正确的HTTPS服务器,或者您已经添加了一个适当的异常。

最后,如果您希望包含其他POST参数,而不仅仅是将blob数据作为请求体,则必须使用流请求。当然,您可以使用GET参数,这就是我建议您做的,因为这是一种非常、更容易的方法。:-)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31130721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档