无法使用iOS中的NSURLSession多部分表单数据上传文件

A f*_*pha 14 file-upload multipartform-data nsurlsession nsurlsessionconfiguration nsurlsessionuploadtask

我正在尝试- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; 使用多部分表单数据的方法上传视频/图像文件.但不知何故,我无法上传文件,我收到" stream ended unexpectedly"错误.

要求

  1. 将视频/图像文件上传到服务器
  2. 应用程序应支持后台上传(即使在应用程序进入后台后仍继续上传过程)
  3. 服务器期望使用多部分表单数据发送数据.

方法/ API用于实现此目的

  1. NSURLSession后台会话API(下面列出的完整代码)

    2.- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL

面临的挑战/问题

  1. stream ended unexpectedly每次我使用此API进行上传过程时都会出现" "错误

需要注意的要点

  1. 上传越来越成功的相同的代码,如果我用NSURLConnection的不是NSURLSession.

  2. NSURLSession后台上传进程期望文件location(NSURL)作为参数,不接受NSData.它不允许我们NSData在上传之前将文件转换为,即我们无法将NSData添加到文件体.

需要以下几点的帮助

  1. 在正在形成的multipart formdata主体中是否有任何错误(注意 - 相同的代码与NSURLConnection一起使用)

  2. 我的方法在哪里出错?

  3. 我们是否需要在服务器级别进行任何更改以支持NSURLSession backgroundSession上传?(在数据解析或其他什么?)

    以下是用于上载文件的代码

NSString*BoundaryConstant = @"---------- V2ymHFg03ehbqgZCaKO6jy";

    // string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
    NSString* FileParamConstant = @"file";

    // the server url to which the image (or video) is uploaded. Use your server url here

    url=[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%d",baseURL,@"posts/post/update/",createPostObject.PostID]];    


    // create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:120];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    [request setURL:url];

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    if([[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"]){

        [request setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"] forHTTPHeaderField:AccessTokenKey];

    }

    // post body
    NSMutableData *body = [NSMutableData data];

    // add params (all params are strings)
    for (NSString *param in self.postParams) {

        NSLog(@"param is %@",param);

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param]             dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [self.postParams objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    // add video file name to body

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"file.mp4\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: video/mp4\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
      //  [body appendData:self.dataToPost];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];



    // setting the body of the post to the request
    [request setHTTPBody:body];

    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

    NSURLSessionConfiguration * backgroundConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"backgroundtask1"];

    NSURLSession *backgroundSeesion = [NSURLSession sessionWithConfiguration: backgroundConfig delegate:self delegateQueue: [NSOperationQueue mainQueue]];


    NSURLSessionUploadTask *uploadTask = [backgroundSeesion uploadTaskWithRequest:request fromFile:self.videoUrl];
    [uploadTask resume];
Run Code Online (Sandbox Code Playgroud)

dga*_*ood 12

您没有上传您认为自己的内容.您的目的是按原样上传正文数据.相反,当您调用时uploadTaskWithRequest:fromFile:,该方法会有效地删除请求中的任何值HTTPBodyHTTPBodyStream值,并将其替换为您通过fromFile:参数传入的URL的内容.

因此,除非您将表单编码的正文数据块写入其他位置的文件URL,否则您将自行上载文件而不是多部分表单数据.

您需要调整代码以将表单数据写入文件而不是将其存储HTTPBody,然后将该文件的URL传递给fromFile:参数.


Vic*_*asé 5

为了防止浪费时间处理它.

基于@dgatwood答案的完整代码片段

private func http(request: URLRequest){
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
        /*Tweaking*/
        let task = session.uploadTask(with: request, from: request.httpBody!)
        task.resume()
    }
Run Code Online (Sandbox Code Playgroud)

并且..不要忘记在请求对象上添加Headers

request.setValue("multipart/form-data; boundary=\(yourboundary)", forHTTPHeaderField: "Content-Type")
Run Code Online (Sandbox Code Playgroud)