【问题标题】:NSURLSessionUploadTask failed to upload fileNSURLSessionUploadTask 上传文件失败
【发布时间】:2015-09-16 19:18:05
【问题描述】:

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

我还想将参数与文件上传一起发布。

我也不擅长服务器端代码。谁能指导我做错了什么。

上传代码

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 的空数组

【问题讨论】:

    标签: php ios file-upload nsurlconnection nsurlsession


    【解决方案1】:

    如果这是完整的代码,那么您实际上并没有开始上传。 NSURLSession 任务不会自动启动(与某些 NSURLConnection 调用不同)。您必须显式调用他们的 resume 方法才能开始上传,否则任务将坐在那里什么都不做。

    其次,您应该真正使用 URLForResource 而不是使用路径然后将其转换为 URL。这不应该破坏您的代码,但仅使用 URL 开始会更简洁。

    第三,如果你真的需要使用路径,方便的方法(fileURLWithPath:)是你的朋友。

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

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

    第六,如果您在较新版本的 iOS 或 OS X 上运行,请确保您使用的是正确配置的 HTTPS 服务器,或者您已添加合适的应用程序传输安全例外。

    最后,如果您想包含其他 POST 参数,而不仅仅是提供数据块作为请求正文,则必须使用流式请求。当然,您可以简单地使用 GET 参数,这就是我建议您这样做的方法,因为它是一种更简单的做事方式。 :-)

    【讨论】:

      【解决方案2】:

      我会放一个代码示例。检查您是否在控制台上收到任何错误。

      // 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);
            }
      }];
      

      【讨论】:

      • 我使用的不是默认的后台会话,后台会话中也不允许完成处理程序。另外,NSData 作为图像也不允许作为图像。
      猜你喜欢
      • 2013-06-09
      • 2012-03-18
      • 1970-01-01
      • 2013-07-09
      • 2020-06-12
      • 2012-05-31
      相关资源
      最近更新 更多