首页 > 解决方案 > 文件上传到 Web 服务,在 Objective C 中不起作用

问题描述

我需要一些额外的眼睛。下面的代码根本没有触发:

NSString *apiUrl = @"<WEB SERVICE URL>";
NSString *theFileName = [file_path lastPathComponent];

NSArray *parameters = @[ @{ @"name": @"file", @"fileName": theFileName, @"file_path" : file_path } ];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSData *imageData = [NSData dataWithContentsOfFile:file_path];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
     [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    if (param[@"fileName"]) {
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n",param[@"name"] , param[@"fileName"]] dataUsingEncoding:NSUTF8StringEncoding]];
         [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        if (error) {
            NSLog(@"%@", error);
        }
    } else {
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n",param[@"name"]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@", param[@"value"]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
}
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = body;

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrl]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

我整天都在看这个,似乎找不到我所缺少的东西。

基本上我正在尝试重写我的旧文件上传,它使用 sendSynchronousRequest,女巫有效,但已被弃用。

旧的工作代码。

    NSString * urlString = @"<WEB SERVICE URL>";
        NSString *theFileName = [path lastPathComponent];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];

        [request setHTTPMethod:@"POST"];
        NSMutableData *body = [NSMutableData data];
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        NSData *imageData = [NSData dataWithContentsOfFile:path];

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", theFileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


        // close form
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


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


        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];


        //NSLog(@"File posted");
        return dict;
    }else{
       // NSLog(@"upload failed");
    }

一直在寻找指针,但还没有设法提出一个可行的解决方案。

标签: objective-cfile-upload

解决方案


似乎您忘记设置内容类型标头:

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

另外,移动这个:

[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

到块的末尾for而不是块的外面,因为每个部分都需要这个 line-end。

最后一点:所有都Content-Disposition:应该以两个结尾,所以在->\r\n之后添加一个filename=\"%@\"\r\nfilename=\"%@\"\r\n\r\n


推荐阅读