NSURLConnection图像上传到服务器错误

时间:2014-02-14 06:57:59

标签: objective-c iphone cocoa-touch nsurlconnection

快速提问。

我试图像所描述的Curl函数那样做

curl -v -F content=@/home/user/Downloads/test.jpg “http://...:8088/upload?session=(blabla)&conv=(blabla)"

出于某种原因,我的所有上传都失败了。这是我的代码。

 // create request

static NSString *boundary = @"---------------------------14737809831466499882746641449";
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)];

NSMutableURLRequest *request;
request= [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:8088/upload?session=%@&conv=%@", kQAServer, session , conv]]];
[request setHTTPMethod:@"POST"];


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

// add image data
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"content\"; \r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:imageData];
[postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];


NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
                                      returningResponse:&response
                                                  error:&error];

if (error == nil)
{
    NSString *fileID = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return fileID;
}

return nil;

1 个答案:

答案 0 :(得分:0)

请勿使用error == nil检查命令是否成功。该命令可以在没有错误的情况下失败,并且可以成功执行。 (这是作为错误的整个伪协议的一部分记录的。)

而只是检查您是否有数据。如果data == nil您遇到了硬错误,则应记录错误。

(如果您确实有数据== nil,请发布错误,我们可以提供帮助。)