我想使用{strong} fileUrl API使用NSURLSessionUploadTask
上传大文件。以下代码是我写的上传大文件的代码。我发现了这些问题:
-URLSession:task:didCompleteWithError:
中出现“超时”错误。在已发送的软件包中找不到 http正文(通过使用wireshark)。这是我的代码:
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSURL *url = [My URL];
fileName = [[DBList objectAtIndex:fileIndex] objectForKey:@"title"];
NSString *boundary = [self getBoundaryStr];
NSMutableData *dataSend = [[NSMutableData alloc] init];
[dataSend appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"target_path"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"/%@",[NSString stringWithFormat:@"%@/%@/%@",UploaderController.getDestination,APP_UPLOADER,[Functions getDateString]]] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_path\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[dataSend appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
[request setValue:[@"authtok=" stringByAppendingString:[broker getNasAuthtok]] forHTTPHeaderField:@"Cookie"];
[request setHTTPBody:dataSend];
NSString *tempFile = [NSTemporaryDirectory() stringByAppendingPathComponent:@"uploadFile"];
NSURL *uploadfileURL = [[NSURL alloc] initFileURLWithPath:tempFile];
NSURLSessionUploadTask *sessionUploadTask = [session uploadTaskWithRequest:request fromFile:uploadfileURL];
[sessionUploadTask resume];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
任何人都知道我在哪里错过了?非常感谢!!
或只是像上传视频这样的文件?
答案 0 :(得分:1)
NSURLSessionUploadTask将忽略http正文。
您可以将要上传的文件与您已有的参数一起添加到dataSend对象。然后将dataSend写入本地文件。最后使用该本地文件的url创建uploadTask。
棘手的部分是准备dataSend对象。您可以先尝试使用NSURLConnection发送帖子请求。然后使用上传任务将代码从NSURLConnection迁移到NSURLSession。
答案 1 :(得分:0)
请查看此链接,了解可能出现的问题: