Reputation: 77984
I am facing a very strange issue while uploading an image from iPhone. When I upload image from iPhone,image on server gets created but with 0 size.
I have used many PHP functions to receive image from bytes but all in vain, from iPhone I am sending image an httppost in binary form (multipart content type).
All the code is given below. Following are the various PHP methods that I have used but neither of them is working .
$id=rand() ; // for image name
//=====================1st method========================
if(isset($_REQUEST['image_string'])) {
$imgData =@$_REQUEST['image_string'];
header('Content-Type:image/jpg; charset=utf-8');
$file = fopen("new_arrivals_img/".$id.".jpg", 'wb');
fwrite($file, $binary);
fclose($file);
}
//========================2nd method=====================
if(isset($_REQUEST['image_string'])) {
$imgData =$_REQUEST['image_string'];
$im = imagecreatefromstring($imgData);
$src="new_arrivals_img/".$id.".png";
imagepng($im,$src);
}
//=======================3rd method==================
if(isset($_REQUEST['image_string'])) {
$target_path = "new_arrivals_img/";
$target_path = $target_path.basename($_FILES['image_string']['name']);
move_uploaded_file($_FILES['image_string']['tmp_name'], $target_path);
}
//===================4th method ===========
if(isset($_REQUEST['image_string'])) {
$imageString = file_get_contents($_REQUEST['image_string']);
$save = file_put_contents("new_arrivals_img/".$id.".png",$_REQUEST['image_string']);
}
//==========================5th method =================
if(isset($_REQUEST['image_string'])) {
copy($_REQUEST['image_string'], "new_arrivals_img/".$id.".png");
}
//======6th method =========================================
if(isset($_REQUEST['image_string'])) {
$url = $_REQUEST['image_string'];
$dir = "new_arrivals_img/";
$lfile = fopen($dir . basename($url), "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);
curl_exec($ch);
fclose($lfile);
curl_close($ch);
}
iOs code is given below:
//image_string3 is parameter in which imagedata1 passed and server url is // http://192.95.48.44/image_binary/index.php
NSData *imageData1 = UIImageJPEGRepresentation(myImage,0.2); //change Image to NSData
if (imageData1 != nil)
{
NSString *urlString = @"http://192.95.48.44/image_binary/index.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------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 stringWithString:@"Content-Disposition: form-data; name=\"image_string\"; filename=\"test123.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData1]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSLog(@"body %@",body);
NSLog(@"request %@",request);
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"returning strin %@",returnString);
NSLog(@"finish");
}
Upvotes: 0
Views: 291
Reputation: 77984
After spending two days on this issue, i finally got the solution, it was issue in my server that was not allowing me to create image dynamically or through programming.
Although i had given full rights (read,write,update or 777) to my folder where i was creating image.
i just changed the server and it worked perfectly, the code i was using and the one provided by AdamG both worked for me.
Upvotes: 1
Reputation: 3718
I think that your function in Objective-C is correct. However, I think the PHP side methods you are using are incorrect. This is the one that I use and it works perfectly:
function uploadPicture(){
if ($_FILES["file"]["name"] == "noimage.jpg"){
return "noimage.jpg";
}
$uploadLocation = "failed";
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
echo "file size" . ($_FILES["file"]["size"] / 1024) . "KB";
if (($_FILES["file"]["size"] < 500000) && in_array($extension, $allowedExts)){
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$uploadLocation = "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "invalid file";
}
return $uploadLocation;
}
For thoroughness I will add the method that I am using on the Objective-C side so you can compare if you find the server side isn't the issue. However, as I said before, I think your method is fine, and the issue is on the server side and I checked through both of our code pretty thoroughly to make sure they were the same.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString * boundary = @"qerklasdfe2309asdf123asdfjkl";
// the file name comes from the user_id as the first character, and a random string 20 characters long as the second
// there is a negligable chance of repititions here
NSString * fileName = [[NSString alloc] initWithFormat:@"%@%@", params[@"user_id"], [[self class] genRandStringLength:20]];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
if (image == nil){
NSLog(@"empty image");
fileName = @"noimage";
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n", @"file", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// add params (all params are strings)
for (NSString *param in params) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", params[param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
// set URL
NSURL * requestURL = [NSURL URLWithString:@"http://www.mywebsite.com/myscript.php"];
[request setURL:requestURL];
;
NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(@"%@", theConnection);
Upvotes: 2