从 iPhone/ipad 上传一些图片到我的网络服务器时遇到问题。确实,我的代码在 MAC 上的模拟器 iPhone 上运行良好,但在真实设备上,它不起作用,图片没有上传到我的服务器上。我不知道问题出在哪里以及为什么它在模拟器上而不是在我的设备上有效。我在 objc 中有这段代码,我调用一个 php 文件将图像保存到服务器。
目标c代码:
NSData *storeData = UIImageJPEGRepresentation(pictureItem, 90);
NSString *URLString = @"http://url_example/upload.php"; //call upload.php
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------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 stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%d.jpg\"\r\n", idItem] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:storeData]];
[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文件在这里:
<?php
$uploaddir = './'; //Uploading to same directory as PHP file
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$newName = $uploadDir . $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']> 10000000) {
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');
}
?>
谢谢您的帮助!