Flutter web file upload - php

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);

Related

I want to upload multiple file to sever using flutter and php, but only one file is being uploaded

Here is flutter code
var file = await http.MultipartFile.fromPath("file", _file[0].path);
var file2 = await http.MultipartFile.fromPath("file2", _file[1].path);
var file3 = await http.MultipartFile.fromPath("file3", _file[2].path);
request.files.add(file);
request.files.add(file2);
request.files.add(file3);
http.StreamedResponse response = await request.send();`
here is php code
<?php
$file = $_FILES['file']['name'];
$file2 = $_FILES['file2']['name'];
$file3 = $_FILES['file3']['name'];
$imagePath = 'upload/'.$file;
$imagePath2 = 'upload/'.$file2;
$imagePath3 = 'upload/'.$file3;
$tmp_name = $_FILES['file']['tmp_name'];
$tmp_name2 = $_FILES['file2']['tmp_name2'];
$tmp_name3 = $_FILES['file3']['tmp_name3'];
move_uploaded_file($tmp_name,$imagePath);
move_uploaded_file($tmp_name2,$imagePath2);
move_uploaded_file($tmp_name3,$imagePath3);
?>
I am trying to upload three files to server but only one file is uploaded
I hope this will work
Map<String, String> headers = <String, String>{
"Content-Type": "multipart/form-data",
};
request.files.add(await http.MultipartFile.fromPath('file', file1));
request.files.add(await http.MultipartFile.fromPath('file2', file2));
request.headers.addAll(headers);
http.Response rootResponse = await http.Response.fromStream(
await request.send());

React-Native Base 64 Data to FileSystem issue

I have a very simple PHP file that returns my image as BASE64 data
<?php
require_once 'database_connections.php';
$data = json_decode(file_get_contents("php://input"));
$id = mysqli_real_escape_string($con, $data->id);
$page = mysqli_real_escape_string($con, $data->page);
$path = "../../images/" . $id . '/' . $page . '.jpg';
$imagedata = file_get_contents($path);
$base64 = base64_encode($imagedata);
echo($base64);
?>
In my react app, I am fetching this data like below
export const getImage = async () => {
try {
const response = await axios.post(
url,
{
id: '11bb2c1b-c262-4171-b614-d8af46898efb',
page: '001',
}
);
return response.data;
} catch (error) {
// handle error
console.error(error.message);
}
};
my base64 response like below:
/9j/2wCEAAEBAQEBAQEBAQECAQEBAgICAQECAgICAgICAgIDAgMDAw...
and finally my FileSystem code is like below:
const image = await getImage();
const filename = FileSystem.documentDirectory + 'imagetest.jpg';
await FileSystem.writeAsStringAsync(filename, image, {
encoding: FileSystem.EncodingType.Base64,
});
I'm not getting any error but my file is not being saved as I try. I have been working on this for hours but didn't solve my issue.
any advice would be appreciated!
Edit: I can show the base64 image in an Image component.
you wont be able to see your saved image file in FileSystem.documentDirectory , you need to
FileSystem.readDirectoryAsync(FileSystem.documentDirectory).then(data => {
data.forEach(filename_ => {
console.log("=cached image==***===" + filename_)
})
to check if it is there. FileSystem.documentDirectory is only "pragmatically accessible"

Decode Base64 string in PHP recieved from JSON post

I'm working on a project where i can select an image (simple file select) and send it via JSON to a PHP MySQL insert page.
Upload page looks like this:
if (input.files && input.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
var Naam = $('input[type=file]').val();
$('#base').text(e.target.result);
var Foto = e.target.result;
var Barcode = $('#barcode').val();
obj['Barcode'] = Barcode;
obj['Naam'] = Naam;
obj['Foto'] = Foto;
//execute ajax send
$.ajax({
url : 'insert.php',
type : 'POST',
data : obj,
dataType : 'json',
success : function(msg) {
alert("msg");
}
});
//$.post("insert.php", obj, function (data) {}, "json");
//alert("msg");
};
FR.readAsDataURL(input.files[0]);
and my PHP page:
$Barcode = $_POST["Barcode"];
$Naam = $_POST["Naam"];
$Name = preg_replace('/^.+[\\\\\\/]/', '', $Naam);
$Foto = base64_decode($_POST["Foto"]);
$query = "INSERT INTO voorraad_foto (barbody, location, foto) VALUES ('$Barcode','$Name','{$Foto}')";
$results = mysqli_query($db,$query);
And my table field is a BLOB.
But when it execute this, everything works fine except that it doesn't insert it as a blob, but pure string
I've tried with removing the
preg_replace('#data:image/[^;]+;base64,#', '', $Foto)
but doesn't make any difference, same when trying to add headers, but nothing..
What am i doing wrong, or is there something obvious that i'm not getting?
Thx.
I solved it in some kind of way:
I wrote a function that gets the Base64 string, decodes it and writes it to a Temp file.
Then i read that file again and upload that to my databse.
When success, delete the file.
It may not be the most effecient way, but it works!
function WriteToImageAndGetData($base64_string, $File) {
//Write to file
$ifp = fopen($File, "wb");
$data = explode(',', $base64_string); //Split Base64 string
fwrite($ifp, base64_decode($data[1])); //Decode Base64 string
fclose($ifp);
//Read from file
$fp = fopen($File, 'r');
$data = fread($fp, filesize($File)); //Read file contents
$data = addslashes($data);
fclose($fp);
return $data;
}

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="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA//asAP9L/9v/S//b//asAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/S//b/0v/2//2rAD/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
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.

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