我正在发送一张构建 HTTP POST 的图片,如下所示:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"801f6dd4cd17";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=------------------------------%@", boundary];
NSMutableDictionary *headerFieldsDict = [[ NSMutableDictionary alloc] init];
[ headerFieldsDict setObject:contentType forKey:@"Content-Type"];
[request setAllHTTPHeaderFields:headerFieldsDict];
NSMutableData *body = [NSMutableData data];
//---------- FIRST IMG
UIImage* imgLittle = [realImgButton imageForState:UIControlStateNormal];//thumImg.image;
NSData *imageData = UIImageJPEGRepresentation(imgLittle, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"------------------------------%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"img.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"------------------------------%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
但是服务器拒绝上传图像(它给出了一个软件错误,似乎 HTTP 帖子没有很好地解析),我关于服务器的唯一信息是这个客户端代码在 php 中运行良好:
$data['file'] = "@".$file;
$header[] = "Expect: ";
print_r($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
//curl_setopt($ch, CURLOPT_URL, 'http://xxxxxx:yyy/');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
$url = strip_tags($xml->dict->string[3]->asXML());
return $url;
有任何想法吗?或者我在 obj-c 代码上哪里错了?我尝试分析生成的 HTTP post 语句,它似乎与 php 代码生成的语句相同。