Uploading A Base64 encode Image to php server - php

how do i upload a Base64 encoded image to a PHP server using HttpURLConnection? All the answers i have seen so far are based on HttpClient which no longer exists. I got a httprequest.java library that sends post request to the server, the problem i have with it is that the image string at the server-side is always different to the one i send.
This is my code so far.
HttpRequest request = new HttpRequest(Konstants.address+Konstants.save_image);
request.prepare(HttpRequest.Method.POST);
String encodedImage = Base64.encodeToString(image, Base64.URL_SAFE);
//image is a byte[] with image data
HashMap<String, String>map = new HashMap<>();
map.put("username",username);
map.put("image", encodedImage);
Log.d("IMAGE-DATA", encodedImage);
request.withData(map);
JSONObject object = request.sendAndReadJSON();
code = object.getInt("response_code");
if (code == 0)
flag = Boolean.FALSE;
String s = object.getString("response_message");
Log.d("SERVER-REPLY", s);
//encodedImage and s are different
and the PHP code below:
<?php
if(!$_SERVER['REQUEST_METHOD']=='POST'){
$response["response_code"] = 0;
$response["response_message"] = "INVALID REQUEST";
die(json_encode($response));
}
if (empty($_POST)) {
$response["response_code"] = 0;
$response["response_message"] = "One or both of the fields are empty .";
die(json_encode($response));
}
$username1 = urldecode($_POST['username']);
$data = $_POST['image'];
$binary = base64_decode($data);
list($path, $tmp) = explode(".", $username1);
$success = file_put_contents("./images/$path.png", $binary);
if ($success){
$response["response_message"]=$data;
$response["response_code"] = 1;
}else{
$response["response_message"]="failure";
$response["response_code"] = 0;
}
echo json_encode($response);
?>

Look into the differences. Sometimes you need to replace spaces with plusses.
$binary = base64_decode(str_replace(" ", "+", $_POST['image']));

Related

Flutter web file upload

void _uploadFile(Event event) async {
print("called");
final files = uploadInput.files;
final file = files![0];
_fileNameController.text = file.name;
// Get the file contents as a List<int>
final reader = new FileReader();
reader.readAsArrayBuffer(file);
await reader.onLoad.first;
final contents = reader.result as List<int>;
// Encode the file contents as a base64 string
final encodedFile = base64Encode(contents);
var response = await http.post(Uri.parse("http://url/img_test/img.php"),
body: jsonEncode(<String, String>{
'file': encodedFile,
})
);
print(response.body);
if (response.statusCode == 200) {
// Handle the success case
print("ok");
} else {
// Handle the error case
print("try");
}
}
I all ready set as file in body but till it shows
Error shows in flutter
Warning: Undefined array key "file" in M:\WEB\htdocs\img_test\img.php on line 7
PHP API:
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
?>
your request post not send file, this string value, you can try decode in your php file like this
$base64string = "data:image/jpeg;base64,".$POST['file'];
list($type, $base64string) = explode(';', $base64string);
list(,$extension) = explode('/',$type);
list(,$base64string) = explode(',', $base64string);
$fileName = uniqid()'.'.$extension;
$imageFile = base64_decode($base64string);
file_put_contents($path.$fileName, $imageFile);

base 64 string from Android to SQL not decoding and store in folder using php

I am sending base64 encode image from Android to SQL server DB but image is not stored in the DB folder. The android step to convert the image into base64 string is mentioned below.
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
After converting image to base64 string using volley i am posting into SQL DB. Then using PHP decode base64 string and save the image path in the DB table. The path is stored but not the image in the folder. What is wrong about it.
PHP code used:
if($_SERVER['REQUEST_METHOD']=='POST'){
$FoodName = $_POST['FoodName'];
$FoodLocation = $_POST['FoodLocation'];
$ShopName = $_POST['ShopName'];
$Type = $_POST['Type'];
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM Volley ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "images/New folder/$id.jpg";
$actualpath = "http://ccc.ccc.com/$path";
$sql = "INSERT INTO Volley (FoodName,FoodLocation,ShopName,Type,image) VALUES ('$FoodName','$FoodLocation','$ShopName','$Type','$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents('$path',base64_decode($image));
echo "Successfully posted";
}else{
echo "Could not post";
}
}else{
echo 'error';
}
BASE 64 from Android:
/9j/4AAQSkZJRgAB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h/wUn/6TG67/wCIg/DX/wCaCv3K/wCFax/9D/on
/gt1b/Gmf8K0tP8Aof8AQ/8Aysf40fWPX/yT/wCSM/q2M/u/fD/I/Db/AIYP/wCClP8A0mQ13/xD
/wCGn/zQ0f8ADB//AAUp/wCkyGu/+If/AA0/+aGv3Q/4Vrb/APQ/6J/4LdX/AMaP+FYW3/Q/eFP/
AAW61/hRzrz+5f8AyRj7CHeX3r/5E/Df/hg//gpT/wBJkNd/8Q/+Gn/zQ0f8MH/8FKf+kyGu/wDi
H/w0/wDmhr9xpfhreTQH+zfFOh6pdcfYbH+0xp2p6lzJ/wBBgE+pH49gxHmGo22p6beXllqdlfWt
za4+3WN8feQf0H6cnGSe2X/Qtf4f5C9gv5n9yPyDP7EH/BT3TIftmkf8FebHVNUtsfYbHxX+xb8M
9R8M8Fs/8gfXzjtj6sTncpHnmt/tYftc/sS6zoWm/wDBS34WeBte+C2va3pnhax/bk/ZkbxiPhp4
J1PUGZdIH7R3whLDWvhUTwR4hX/imGJGFO3cf2yWdmyN3Hf5h6n3z2H5+xqhrnhvwz4y8P8AiHwP
4r0Gx8VeDvGWh6n4U8V+FPFelnxF4a8SeGdRLf2xo+s6Rn/ifZ7987jyKwWJwiTWMV1p1S+1LW7d
03pfdaxbTukNUI95OzV7Nbar+V2e1tX11b1PFIrrStU0iHUHurXV9JutP0zW7PW/DurfbLHxNpOp
lxpOr6FrZB/tnRiCfLkOSrkvzt5K/ND9hjStb/Zw+M/7T/8AwTKv/EF5rvgr9n+78NfG79lPXfF2
pnUfEX/DLHxZymjfDh21didnwn8aLr/h9zgEEkAZDGijG5XiliKiu3trte8pP+ZK6vZ20u7XT0OJ
O19V03du/ZbPe/nqr3O9/YS/0z/gpl/wWHvLz/SrrS779izQr
If your base64encoded string has data:image/jpeg;base64, appended infront of it, then you need to remove it before base64_decode
You can use something like this for it
str_replace("data:image/jpeg;base64,","",$image);
UPDATE
I tried to convert your string here But it seems to be corrupted. The base64 string is not proper.
This might happen, if there are new line characters in the code. So try replacing \n or any other white spaces from the string before decoding it. You can use str_replace("\n", "", $image) for that as well. Try and let me know

imagecreatefromstring is causing 500 internal server error

I have bitmao instance i convert this instance into base64string and send it to server over php function. Now i am decoding this string and calling imagecreatefromstring but this function is giving 500 internal server error. I want this image to be store into file.
My .net function is as follows:
Bitmap icon = new Bitmap("C:\\Users\\HP\\Desktop\\mun.ico");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php"+ "?bitmap=" + base64String; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
My php code to handle this encoded bitmap string is as follows:
$bitmap=$_GET['bitmap'];
$data = base64_decode($bitmap);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
encoded bitmap string is as follows:
$bitmap="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
why i am getting this error on imagecreate from string?
BMP format is not supported by imagecreatefromstring. Allowed formats are: JPEG, PNG, GIF, WBMP, and GD2.

WindowsPhone 8 - Upload image to php page

I already searched for a lot of different tutorials on how to upload an image from an windowsphonen 8 app to my php page (fileserver) - nothing works for me, so I 'm asking you.
This is my code to convert a Stream to Base64
string PhotoStreamToBase64(Stream PhotoStream)
{
MemoryStream memoryStream = new MemoryStream();
PhotoStream.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
string base64img = System.Convert.ToBase64String(result);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += 32766)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(32766, base64img.Length - i))));
}
return sb.ToString();
}
I catch the Image using photoChooserTask (this works fine, but I dont get a Stream I can use for the other Method)
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
}
}
To Upload the image I tried this:
public void UploadImageAsync(Stream PhotoStream)
{
try
{
WebClient w = new WebClient();
w.Headers["Content-type"] = "application/x-www-form-urlencoded";
string data = "id=1" +
"&_fake_status=200" +
"&type=base64" +
"&image=" + PhotoStreamToBase64(PhotoStream);
w.UploadStringAsync(new Uri("http://myurl.de/php/app/changeimg.php", UriKind.Absolute), "POST", data);
}
catch (Exception ex)
{
}
}
The last part is my php file
function base64_to_image( $imageData, $outputfile ) {
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
return( $outputfile );
}
if (isset($_POST['image'])) {
base64_to_jpeg($_POST['image'], "test".$_GET['id'].".jpg");
$file = 'people.txt';
$person = "Win";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
}
else
{
die("no image data found");
$file = 'people.txt';
$person = "Fail";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
}
I got all these code snippets from different sources and somehow thought it's the best "idea" I could find. Does anyone maybe have an example code for my Problem? I 'm really new to Windowsphone dev and I need some serious help on that problem.
First off all, do not use WebClient class, use HttpClient and its method PostAsync and then it completely dependent on your Web API implementation

uploading image and php POST method in windows phone

this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/

Categories