我正在尝试运行 HTTP 请求以保存图像。PHP脚本处理POST,它似乎接收到手动设置的文件名,但文件没有大小也没有保存。
我正在使用的 Obj-C 代码是:
MyImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 90);
NSString *urlString = @"http://localhost/api/phptest.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
我的 PHP 文件看起来像:
//echo basename($_FILES['userfile']['name']);
$uploaddir = '/api/uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
echo $uploadfile."\n";
echo $file."\n";
echo $uploaddir."\n";
echo $_FILES["file"]["type"]."\n";
echo $_FILES["file"]["size"] / 1024;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Uploaded";
}
但是我在 XCode 中得到的回报是
2013-02-10 13:23:09.116 Dablia[3419:907] /api/uploads/ipodfile.jpg
ipodfile.jpg
/api/uploads/
0