嗯,我对iphone和PHP开发都很陌生,我试图在本地将图像发布到我的网络服务器上(我已经设置了网络服务器)。出于某种原因,我的PHP脚本正在执行,但文件没有被保存。
我确信这是最基本的问题,但我似乎无法找到问题所在。真的很感谢你们的帮助。谢谢!
我的目标-c代码:
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:@"13.png"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = @"http://localhost/uploader.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setTimeoutInterval:60.0];
[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=\"myfile.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];
NSLog(@"%@",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
我的PHP脚本:
<?php
$target = "./upload/";
$target = $target.basename( $_FILES['userfile']['name']) ;
$check = getimagesize($_FILES['userfile']['tmp_name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], './upload/')) {
echo "YES";
}
else
echo "NO";
?>
这些是我在PHP中打印这些变量时得到的值:
print_r($target);
./upload/myfile.jpg
print_r($check[0]);
320
print_r($_REQUEST);
Array
(
)
print_r($_FILES[userfile]);
Array
(
[name] => myfile.jpg
[type] => application/octet-stream
[tmp_name] => /private/var/tmp/phpWJE4UC
[error] => 0
[size] => 8829
)
print_r($_FILES[name]):
(empty)
print_r($_FILES[type]);
(empty)
print_r($_FILES[tmp_name]);
(empty)
print_r($_FILES[error]);
(empty)
print_r($_FILES[size]);
(empty)
print_r($_FILES);
Array
(
[userfile] => Array
(
[name] => myfile.jpg
[type] => application/octet-stream
[tmp_name] => /private/var/tmp/phpMvJ4oR
[error] => 0
[size] => 8829
)
)
答案 0 :(得分:2)
您的移动电话不正确。您必须为目标指定文件名。您只提供了一个目录,因此调用失败。 PHP不会为您创建文件名,您必须自己指定。
if (move_uploaded_file($_FILES['userfile']['tmp_name'], './upload/name_of_file_to_write')) {
^^^^^^^^^^^^^^^^^^^^^