我需要将图片从 iphone 应用程序上传到服务器。
我使用此代码在 localhost 上尝试:
NSData *storeData = UIImageJPEGRepresentation(pictureItem, 90);
NSString *URLString = @"http://localhost:8080/image_item/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:[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);
使用 image_item 我的文件夹来存储图像, idItem 是图片的名称。
我调用了一个 upload.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']> 300000) {
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');
}
?>
但问题如下:文件夹中有我的图片,名称好,但我无法打开图片。出现以下错误:它可能已损坏或使用了预览无法识别的文件格式。
所以我不明白......有人可以帮助我吗?
谢谢。