0

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

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

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

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

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

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

但根据我能找到的示例、关于 so 的问题和 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's AFHTTPRequestSerializer,它在您构建表单数据时提供输入名称,但由于其他原因这对我不起作用。

任何帮助,将不胜感激。

4

1 回答 1

1

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

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

可以按照Apple 文档中的描述生成 url 编码的数据 blob,并添加几个 (__bridge_transfer NSString *) 和 (__bridge CFStringRef) 位。:-)

话虽如此,Stack Overflow 上已经有一个不错的多部分表单数据示例。请注意,当您实际使用边界时,会在边界的前面添加两个额外的连字符,因此如果您指定“foo”作为边界,那么每个部分之间都会有“--foo”。

于 2016-07-25T05:50:08.173 回答