我创建了viewcontroller来从图像选择器上传图片并将其发送到php webserver但它没有上传到服务器。 这是我的代码
uploadViewcontroller.m
NSData *picdata = UIImageJPEGRepresentation(imgShow.image, 90);
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:@"http://www.mytestwebsite.com/upload2.php"]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: from-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:picdata]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
和我的PHP代码
<?php
$uploaddir = "post_comment/original/";
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$randomNumber = rand(0, 99999);
$newName = $uploadDir . $randomNumber . $uploadFile;
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "Temp file uploaded. \r\n";
} else {
echo "Temp file not uploaded. \r\n";
}
if ($_FILES['userfile']['size']> 3000000) {
exit("Your file is too large.");
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) {
$postsize = ini_get('post_max_size'); //Not necessary, I was using these
$canupload = ini_get('file_uploads'); //server variables to see what was
$tempdir = ini_get('upload_tmp_dir'); //going wrong.
$maxsize = ini_get('upload_max_filesize');
echo "upload finished" ;
}
?>
答案 0 :(得分:0)
检查这是否有效...它对我有用
$image = $_POST['userfile'];
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
$image = str_replace(" ","",$image);
$image = pack("H*", $image);
$filename = "image.png";
$f = fopen($filename,'wb');
fwrite($f, $image);
fclose($f);