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

2024-04-20

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

要求

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

用于实现此目的的方法/API

  1. NSURLSession后台会话API(完整代码如下)

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

面临的挑战/问题

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

注意事项

  1. 如果我使用相同的代码,上传会成功NSURLConnection代替NSURLSession.

  2. NSURLSession后台上传过程需要文件位置(NSURL) 作为参数,不接受 NSData。它不允许我们将文件转换为NSData在上传之前,即我们不能将 NSData 添加到文件正文中。

需要以下几点帮助

  1. 正在形成的多部分表单数据主体是否有任何错误(注意 - 相同的代码正在使用 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];

您上传的内容并不是您认为的内容。您的意图是按原样上传正文数据。相反,当你打电话时uploadTaskWithRequest:fromFile:,该方法有效地消除了任何HTTPBody or HTTPBodyStream请求中的值,并将它们替换为您通过fromFile:范围。

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐