iPhone から PHP に画像をアップロードしていますが、PHP では画像が表示されません。画像はバイト単位で保存されていました。
-(void)uploadMyImage:(UIImage *)img
{
NSData *data = UIImageJPEGRepresentation(img, 90);
NSMutableString *urlString = [[NSMutableString alloc] init];
[Base64 initialize];
[urlString appendFormat:@"image=%@",[Base64 encode:data]];
NSString *baseurl = @"http://projectleads.info/spirits/images/imageupload1.php" ;
NSData *postData = [urlString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: @"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
resData=[[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[resData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString* newStr = [[NSString alloc] initWithData:resData
encoding:NSUTF8StringEncoding];
}
そして私のphpコードは
<?php
$base=$_REQUEST['image'];
if(empty($base))
{
echo 'No data';
}
else
{
echo $base;
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$dbser='localhost';
$dbuser='spirit';
$dbpwd='123456';
$dbname='spirit';
$db= mysql_connect($dbser,$dbuser,$dbpwd);
$dbcon=mysql_select_db($dbname);
function generate_chars()
{
$num_chars = 4; //max length of random chars
$i = 0;
$my_keys = "123456789abcdefghijklmnopqrstuvwxyz"; //keys to be chosen from
$keys_length = strlen($my_keys);
$url = "";
while($i<$num_chars)
{
$rand_num = mt_rand(1, $keys_length-1);
$url .= $my_keys[$rand_num];
$i++;
}
return $url;
}
function isUnique($chars)
{
//check the uniqueness of the chars
global $link;
$q = "SELECT * FROM `url` WHERE `randname`='".$chars."'";
$r = mysql_query($q, $link);
//echo mysql_num_rows($r); die();
if( mysql_num_rows($r)>0 ):
return false;
else:
return true;
endif;
}
$chars = generate_chars();
while( !isUnique($chars) )
{
$chars = generate_chars();
}
$query=mysql_query("insert into url (randname) values ('".$chars."')");
$test=$chars.".jpg";
$file = fopen($test, 'wb');
fwrite($file, $binary);
fclose($file);
echo 'success';
echo '<img src=test.jpg>';
}
?>