2011-01-10 76 views
0

我正在使用NSMutableURLRequest将图像上传到Web服务器。我认为我的代码是稳定的,因为它适用于大多数用户,但有些用户根本无法上传任何图像。看着我的服务器日志,我看到偶尔NSMutableURLRequest偶尔出现“无边界”错误

“中的multipart/form-data发布的数据缺少边界在未知在线0”警告这将指向一个边界错误,构建后的身体。

下面是我使用的是什么:

request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:[method uppercaseString]]; 

NSString *boundary = @"---------------------------14737809831466499882746641449"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary]; 

[request setValue:contentType forHTTPHeaderField:@"Content-type"]; 
NSMutableData *postBody = [NSMutableData data]; 

// add the image 
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[@"Content-Disposition: form-data; name=\"image_upload\"; filename=\"upload.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
NSData *jpegData = UIImageJPEGRepresentation(jpeg, 100); 
[postBody appendData:jpegData]; 
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

// add the other POST params 
keys = [postdata allKeys]; 
int l = [keys count]; 
for (int i=0; i<l; i++){ 
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", [keys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[postdata objectForKey:[keys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 

我可以理解,如果代码导致了当时的PHP警告100%,但它可能每30个或40个用户发生一次。如果用户得到这个错误,那么对于任何他们试图发布的图片来说,它都是一样的。

任何人都可以立即看到明显的东西,或有任何见解,为什么这将是一个间歇性的问题?

回答

0

原来,问题是这一行:

[request setValue:contentType forHTTPHeaderField:@"Content-type"]; 

这当然应该是:

[request setValue:contentType forHTTPHeaderField:@"Content-Type"]; 

(请注意大小写)。但仍然不确定为什么这打破了只有少数用户的请求。

1

HTTP标头字段不区分大小写,因此无论您使用的是Content-Type,Content-type还是CONTENT-TYPE,都不应该有任何区别。另外,你的回答并不能解释为什么只有少数用户有这个问题。

我对失落的边界有不同的解释,一个基于实际经验。事实证明,一些蜂窝数据提供商,特别是沃达丰,通过代理添加各种自定义标头(如x-up-subno,HTTP_SM_MS_CRYPTED等)来过滤所有HTTP请求。我有现实世界的证据表明,其中一些代理破解形式发布为multipart/form-data,删除头的“边界”属性,从而使表单对于任何服务器都不可解析。