我想将文件从 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
,它在您构建表单数据时提供输入名称,但由于其他原因这对我不起作用。
任何帮助,将不胜感激。