IOS 文件上传的一些问题

husky2008 发布于 2015/01/05 22:54
阅读 2K+
收藏 0
iOS

问题:上传的时候服务器端抱异常

异常信息: Header section has more than 10240 bytes (maybe it is not properly terminated)

如果修改下面代码:

[req setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary] forHTTPHeaderField:@"Content-Type"];

multipart/form-data; boundary=%@ 改为 multipart/form-data; boundary=--%@,就不会抱异常了,但是服务器端解析不到上传的数据。

各位大牛,看看小弟的代码哪里有问题,给指点一下,下面贴出代码。





//上传路径

    
    NSString *rootPath = @"http://localhost:8080/Ios/upload";
    
   // rootPath = [rootPath stringByAppendingFormat:@"?file=%@",@"abc.jpg"];
    
    //utf8编码
    
    rootPath = [rootPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *reqUrl = [NSURL URLWithString:rootPath];
    
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:reqUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
    
    req.HTTPMethod = @"POST"; //post请求
    
    //HTTPBody  请求体设置
    NSMutableData *httpBody = [NSMutableData data];
    
    NSString *strTop = [NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\nContent-Type: %@\n\n",kBoundary,@"file1",@"b.jpg",@"image/jpeg"];
    
    
    NSString *strBottom = [NSString stringWithFormat:@"\n--%@--",kBoundary];
    
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"b.jpg" ofType:nil];
    
    
    NSData *data = [NSData dataWithContentsOfFile:dataPath];
    
    [httpBody appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]];
    [httpBody appendData:data];
    [httpBody appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]];
    
    req.HTTPBody = httpBody;
    

    NSLog(@"httpbody0=%@",httpBody);

//下面这行打印的数据为null,但是上面打印确实有数据。不知道是不是这里引起的

    NSLog(@"httpbody=%@",[[NSString alloc]initWithData:httpBody encoding:NSUTF8StringEncoding]);
    
    //设置请求头
    
    [req setValue:[NSString stringWithFormat:@"%@",@(httpBody.length)] forHTTPHeaderField:@"Content-Length"];
    
    [req setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary] forHTTPHeaderField:@"Content-Type"];
    
    
    
    //发送请求
    [NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            
            NSLog(@"上传异常,%@",connectionError.localizedDescription);
        }else{
            
        }
    }];

加载中
返回顶部
顶部