0

I'm trying to upload a file via a multipart request using NSURLSessionUploadTask via AFNetworking. The request executes and receives a response from the server, but the server is not receiving the data in the form.

iOS code

NSString *urlString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
NSError *error = nil;

NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //
   [formData appendPartWithFileData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:path]]
                               name:@"video"
                           fileName:[path lastPathComponent]
                           mimeType:@"video/mp4"];
} error:&error];

if ([account isAuthenticated]) {;
    NSString *authHeader = [NSString stringWithFormat:@"Bearer %@", account.accessToken];
    [request setAllHTTPHeaderFields:@{@"Authorization": authHeader}];
}

NSURLSessionUploadTask *task = [self uploadTaskWithStreamedRequest:request progress:progress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
    if (error) {

    } else {

    }
}];
[task resume];

Here is the header info for the request from AFNetworkingActivityLogger:

POST 'http://127.0.0.1:8000/upload/': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Bearer 270f985de7ebf0aa49b7ff1cad8377e007141f94";
"Content-Length" = 225974;
"Content-Type" = "multipart/form-data; boundary=Boundary+4597B504492E1006";
"User-Agent" = "Test/1.0 (iPad Simulator; iOS 7.1; Scale/1.00)";
} (null)

I'm using Django on the server side. Here's the test view:

class UploadView(View):

def post(self, request, *args, **kwargs):
    logger.debug("FILES: {0} | DATA: {1}".format(request.FILES, request.POST))
    return HttpResponse(content=json.dumps({"test": "2"}), content_type='application/json')

But both the FILES and POST objects are empty:

FILES: <MultiValueDict: {}> | DATA: <QueryDict: {}>

This works without the multipart request- just sending a POST request without a file upload the QueryDict is populated. One thing I'm unsure about is the fact that the body of the request is "(null)" according to the AFNetworkingActivityLogger output.

Any help is appreciated! I'm stumped.

4

1 回答 1

1

来自 -[NSURLSession uploadTaskWithStreamedRequest:] 的文档(看起来这就是您正在使用的):

... 忽略此请求对象中的正文流和正文数据,NSURLSession 调用其委托的 URLSession:task:needNewBodyStream: 方法来提供正文数据。

你实现了那个委托方法吗?

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/doc/uid/TP40013435-CH1-SW28

于 2014-07-29T23:17:01.717 回答