How to save multiple decoded base64 images into database in php? - php

I am designing a app in phonegap. I send multiple base64 images to php webservice. Now i need to decode all those base64 images and save them into database.
I am hoping for the best solution. Thank you.
This is my code for assigning base64 values into a hidden input type.
for(i = 0; i< image.length;i++){
$('#table_postad').append('<input type="hidden" value="'+image[i]+'" name="ad_image'+i+'" class="ad_image"/>');
imageArray.push(document.getElementsByClassName("ad_image")[i].value);
}
Following is the code to connect server:
var server = 'http://example.com/webServiceForProject/';
function sendDataToServer(){
alert("access");
var datas = $("#form_description").serialize();//form_description is id for form
console.log(datas);
$.ajax({
type: 'POST',
data: datas,
url: server+'insert.php',
success: function(data){
alert(data);
},
error: function(){
alert('There was an error adding your comment');
}
});
}
this is php code:
<?php
define('UPLOAD_DIR', 'images/');
$adPhotos = array();
$i=0;
while(isset($_POST["ad_image".$i])){
array_push($adPhotos,($_POST["ad_image".$i]));
$i++;
echo($adPhotos[i]);
}
$j = 0;
while(sizeof($adPhotos)){
$adPhotos[$j]= str_replace('data:image/png;base64,', '', $adPhotos[$j]);
$adPhotos[$j]= str_replace(' ', '+', $adPhotos[$j]);
$file[$j] = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file[$j], $data[$j]);
j++;
}
//insert code here.....
?>

Use php's base64_decode to decode the image and save it to your database (e.g. with mysql_query and an INSERT INTO...-statement.

Ram, you don't have to convert images to base64. Please use this code.
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {}
function browseImage() {
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 80,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/api/upload.php", win, fail, options);
}
function win(r) {
console.log("Response Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log("Error: Code = " = error.code);
}
</script>
<input type="button" onclick= "browseImage()" value="Browse Image" />
//Server: PHP code to upload file
$img_name = $time."jpg";
if(move_uploaded_file($_FILES["file"]["tmp_name"], "folder/".$img_name)){ //upload files in location folder/
//use mysql query to save the filename. (mysql_query("insert into tbl_name(image) values('$img_name')"))
}

Related

Failed upload image to server with base64Encode

I use image picker to get photo from camera then upload it to the server with base64Encode, like this
http.post( api('file/update_pic_item/2'), body: data, headers: {HttpHeaders.authorizationHeader: prefs.getString('token'), "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"}).then((response) async {
toast('Success');
Map res = json.decode(response.body); print(res);
});
By server I got this message
The pic1 must be an image., The pic1 must be a file of type: jpeg, jpg, bmp, png
I use lumen for my backend,
$this->validate($request, [
'pic1' => 'nullable|image|mimes:jpeg,jpg,bmp,png|max:10240', ]);
$upload_path = 'images/items';
if ($request->hasFile('pic1')) {
$pic1 = $request->file('pic1');
$ext1 = $pic1->getClientOriginalExtension();
if ($pic1->isValid()) {
$pic_name = Carbon::now()->format('YmdHs') . "a." . $ext1;
$pic1->move($upload_path, $pic_name);
$item->update(['pic1' => $pic_name]);
}
}
How to solve this problem? thank you so much for your help
Use this code to upload image on server
Future upload(File imageFile)async{
var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length= await imageFile.length();
var uri = Uri.parse('imageUrl');
var request = new http.MultipartRequest("POST", uri);
var imageUri = 'salati_${widget.user.user_id}_${DateTime.now().millisecondsSinceEpoch}'+imageFile.path.substring(imageFile.path.lastIndexOf("."));
var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(imageUri));
request.files.add(multipartFile);
var response = await request.send();
if(response.statusCode==200){
print("Image Uploaded");
}else{
print("Upload Failed");
}
}

Error 403 when trying to upload image using TinyMCE

I'm trying to upload images through TinyMCE but am getting "HTTP Error: 403" shown in the editor itself. I've taken the code from the website for both the script and the php page respectively:
tinymce.init({
selector: "textarea",
plugins: "link image",
height:300,
setup: function (editor) {
editor.on('change', function () {editor.save();});
},
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'queries/editorImageUpload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
And then within 'editorImageUpload.php', I think the problem is to do with the $accepted_origins part as its returning a 403 error:
$accepted_origins = array("https://localhost", "https://77.104.172.194");
$imageFolder = "pictures/Test/";
reset ($_FILES);
$temp = current($_FILES);
if (is_uploaded_file($temp['tmp_name'])){
if (isset($_SERVER['HTTP_ORIGIN'])) {
// same-origin requests won't set an origin. If the origin is set, it must be valid.
if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
} else {
header("HTTP/1.1 403 Origin Denied");
return;
}
}
Any insight on this would be very helpful.
First of all you have two problems with your code
-your php code does not transfer the image to the server
-in your php code you are making array of $accepted_origins with "https://localhost" and you forget the unsecured version "http://localhost"
so the fastest fix for your problem is to write valid php code that will transfer the image to your server and return the image full path for the editor here is the php code
editorImageUpload.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'images';
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$file_name = substr(md5(rand(1, 213213212)), 1, 5) . "_" . str_replace(array('\'', '"', ' ', '`'), '_', $_FILES['file']['name']);
$targetFile = $targetPath. $file_name;
if(move_uploaded_file($tempFile,$targetFile)){
die( $_SERVER['HTTP_REFERER']. $storeFolder . "/" . $file_name );
}else{
die('Fail');
}
}
?>
and in your javascript callback you have to check for the xhr.response not the xhr.responseText since you are dying with the image full path
Tinymce code
tinymce.init({
selector: "textarea",
plugins: "link image",
height:300,
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'editorImageUpload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
console.log(xhr.response);
//your validation with the responce goes here
success(xhr.response);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});

"Disallowed key characters in global data" with Unicode garbage

Searched through the Overflow to see if I can spot a solution to this issue, but unfortunately nothing seems to be specific enough.
I'm building an Ionic app with a photo upload feature (using the cordova-filetransfer plugin), and have an API endpoint set up to receive the image. The Ionic JS is able to process the image successfully, but the API responds back with the "disallowed keys" error; only it's full of random garbled nonsense.
The clean_input function:
public function clean_input_keys($str)
{
$chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z';
if ( ! preg_match('#^['.$chars.'0-9:_.-]++$#uD', $str))
{
exit('Disallowed key characters in global data: '.$str."\n [GLOBAL vars] \n".Kohana::debug($GLOBALS));
}
return $str;
}
The full response:
Disallowed key characters in global data: '()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÛ
[GLOBAL vars]
<pre>array: </pre>
The uploadImage function from the mobile app:
$scope.uploadImage = function(datetime) {
// Destination URL
var uploadUrl = "url/goes/here";
// File for Upload
var imagePath = $scope.urlForImage($scope.image);
console.log('Path: '+imagePath);
// File name only
var filename = $scope.addZero(datetime.getDate()) + $scope.addZero((datetime.getMonth() + 1)) + datetime.getFullYear() + '-' + $scope.addZero(datetime.getHours()) + $scope.addZero(datetime.getMinutes()) + '-' + $scope.incidentData.store + '-' + $scope.incidentData.location + '.jpg';
filename = filename.replace(/\s+/g, '');
console.log('Filename: '+filename);
var success = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
};
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("Upload error source " + error.source);
console.log("Upload error target " + error.target);
};
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = filename;
options.chunkedMode = false
//mimeType: "multipart/form-data",
options.mimeType = "image/jpeg";
var params = {};
params.fileName = filename;
options.params = params;
var headers = {
"API-Key": "keygoeshere",
"Content-Type": "application/x-www-form-urlencoded"
};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(imagePath, uploadUrl, success, fail, options);
}
And the API endpoint function:
public function upload_image()
{
$this->authorise();
$file_temp = $_FILES['image']['tmp_name'];
$file_name = $_FILES['image']['name'];
$target_path = 'path/goes/here';
if (move_uploaded_file($file_temp, $target_path.$file_name)) {
Kohana::log('debug', 'File received: '.$_FILES['image']['name']);
Kohana::log_save();
} else {
Kohana::log('debug', 'Photo upload failed');
Kohana::log_save();
}
}
Sorry if this is a bit too much code, but I cannot work out for the life of me where this error is stemming from - any advice?
The issue turned out to be the headers: I was posting a header (Content-Type) that the plugin already sends by default; the two were clashing and causing the error.
Removing this header, leaving only the API-Key, has allowed the image to be sent.

Upload an Audio File From Ionic

I am having problems uploading a file with CordovaFileTransfer plugin in ionic.
I have sound file that has been recorded and i need help uploading it.
var targetPath = e.nativeURL;
var win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Sent = " + r.bytesSent);
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=filename;
options.mimeType="audio/wav";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(targetPath, "http://example.come/upload.php", win, fail, options);
And my php script looks like this
header('Access-Control-Allow-Origin: *');
print_r($_FILES);
$new_image_name = "audio.wav";
move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/html/snappycast_uploads/files/".$new_image_name);
Have any idea what I am doing wrong??

How to upload photo into Server using Mosync

I have a problem in uploading photo into server which is taken by camera.
I have tried to used the code in Mosync site but it doesn't work.
In the sample code below,
my app always return "Could not upload photo - error: 3"
app.uploadPhoto = function(fileURL)
{
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = app.getMimeType(options.fileName);
options.params = null;
var transfer = new FileTransfer();
transfer.upload(
fileURL,
"http://dev.mosync.com/mobilelua/PhotoGallery/upload.php",
function(result)
{
alert("Photo uploaded");
},
function(error)
{
alert("Could not upload photo - error: " + error.code);
},
options);
};

Categories