I'm trying to upload an image as a BLOB type and insert it into a MySQL database using queries. I have been breaking my head on this code below.
ID is the string and imagedata is the UIImage content converted as NSData.
NSString *urlToUpload = [[@"http://" stringByAppendingString:IP] stringByAppendingString:@":8888/uploadBlob.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlToUpload]];
[request setHTTPMethod:@"POST"];
/*
Set Header and content type of your request.
*/
NSString *boundary = @"---------------------------Boundary Line---------------------------";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSString *fileName = [processID stringByReplacingOccurrencesOfString:@" " withString:@"_"];
/*
now lets create the body of the request.
*/
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=\"%@.jpg\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"ID"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",[processID urlEncodeUsingEncoding:NSUTF8StringEncoding]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set body with request.
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
NSData *returnData1 =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString1 = [[NSString alloc] initWithData:returnData1 encoding:NSUTF8StringEncoding];
Here is the PHP script that receives these values:
<?php
$DB_hostname = "localhost";
$DB_Name = "root";
$DB_pass = "pass123";
$target_path = $_FILES['userfile']['name'];
$id = $_POST['ID'];
$image = file_get_contents($target_path);
$con = mysql_connect($DB_Hostname,$DB_Name,$DB_pass) or die(mysql_error());
//echo "test";
mysql_select_db("arcadia_aex", $con);
$sql = "UPDATE vessel_wms_out SET PicFile = '". mysql_real_escape_string($image) ."' WHERE WDRAW_NO = '$id' ";
$res = mysql_query($sql);
if ($res) {
echo "image stored as blob".$id ;
}else{
echo "blob storage failed";
}
mysql_close($con);
?>
Anyidea where im going wrong in this?