ios - 使用 NSURLSessionUploadTask fromFile,如何将 HTML 输入名称与正在上传的文件链接起来?

标签 ios objective-c file-upload nsurlsession nsurlsessionuploadtask

我想将文件从 iOS 设备上传到服务器。我想使用 NSURLSessionUploadTask 并且我希望上传从文件中获取正在上传的文件的内容。

服务器期望收到名为“sightings.zip”的文件。

用于上传的 HTML 表单包含一个名为“fileBean”的输入标签,如下所示:

<input name="fileBean" type="file" />

我认为我需要设置请求,以便它包含正确的“Content-disposition”信息:

Content-Disposition: form-data; name="fileBean"; filename="sightings.zip"

但根据我能找到的示例、有关问题以及 Apple 文档,我不知道如何做到这一点。

我的相关代码如下。

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.allowsCellularAccess = YES;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[operationManager backgroundQueue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[GGPConstants urlFor:GGP_SEND_SIGHTINGS_PATH]];
[request setHTTPMethod:@"POST"];
[request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"Content-Type" forHTTPHeaderField:@"application/zip"];
[request addValue:@"sightings.zip" forHTTPHeaderField:@"fileName"];

// How to get the value for the name and filename into the content disposition as per the line below?    
// Content-Disposition: form-data; name="fileBean"; filename="sightings.zip"

NSURLSessionUploadTask *uploadTask = [session
    uploadTaskWithRequest:request
    fromFile:myFileURL
    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            // Celebrate the successful upload...
        }
}];

过去我使用过AFNetworking AFHTTPRequestSerializer,它在构建表单数据时提供输入名称,但由于其他原因这对我不起作用。

如有任何帮助,我们将不胜感激。

最佳答案

我不推荐使用form-data类型,因为它很容易出错。最好使用 application/x-www-form-urlencoded,它的构造非常简单。在这种格式中,正文数据基本上看起来像 GET 请求,但没有问号,例如

name=foo.jpg&data=[url-encoded data blob here]

其中可以按照 Apple's docs 中的描述生成 url 编码的数据 blob添加了几个 (__bridge_transfer NSString *) 和 (__bridge CFStringRef) 位。 :-)

也就是说,有一个 decent example Stack Overflow 上已经有多部分表单数据了。请注意,当您实际使用它时,您会在边界的前面添加两个额外的连字符,因此如果您指定“foo”作为您的边界,那么您将在每个部分之间有“--foo”。

关于ios - 使用 NSURLSessionUploadTask fromFile,如何将 HTML 输入名称与正在上传的文件链接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739642/

相关文章:

iPhone PLIST 文件上传即将推出二进制文件

ios - 在 spritekit swift 中触摸节点时不播放声音

html - CSS-:focus无法在iOS上使用

ios - UICollectionViewController 中的 ALAssets 不显示图像

spring - 禁用 Controller 的Spring Boot分段上传

php - Jquery 文件上传,在页面加载时设置数据

ios - XCTAssertThrows 在断点处停止

ios - 自定义 CIKernel 和 iOS7

objective-c - NSOutputStream,NSStreamEventHasSpaceAvailable事件过去后如何正确输出数据?

ios - AFNetworking 上传使用 forKey 引用的文件