How can I upload my blob image to azure storage? - php

I am passing my blob url through ajax request, I am trying to save this blob image to azure storage.
it seems I am doing it wrong and can't find any solution on how to do this right.
here is my code:
function identity_verification() {
navigator.getMedia = (navigator.getUserMedia || // use the proper vendor prefix
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia({
video: true
}, function() {
console.log("webcam is available");
$('.modal .modal-content').addClass('modal-large');
var player = document.getElementById('player');
var snapshotCanvas = document.getElementById('snapshot');
var captureButton = document.getElementById('capture');
var handleSuccess = function(stream) {
// Attach the video stream to the video element and autoplay.
player.srcObject = stream;
};
captureButton.addEventListener('click', function() {
var JPEG_QUALITY = 0.5;
var context = snapshot.getContext('2d');
// Draw the video frame to the canvas.
context.drawImage(player, 0, 0, snapshotCanvas.width,
snapshotCanvas.height);
img_b64 = context.canvas.toDataURL('image/png');
//Create blob from DataURL
blob = dataURItoBlob(img_b64)
img = document.createElement("img");
img.src = URL.createObjectURL(blob);
// console.log(img.src)
$.ajax({
method: "POST",
url: "identity",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'file': img.src,
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
});
navigator.mediaDevices.getUserMedia({
video: true
}).then(handleSuccess);
return proctoring_modal.style.display = "flex";
}, function() {
console.log("webcam is not available");
$('.modal .modal-content .modal-header .modal_header_title').text("");
$('.modal .modal-content .modal-action').empty().append('<button class="">Close</button>');
return proctoring_modal.style.display = "flex";
});
}
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: mimeString
});
}
public function store(Request $request)
{
$src = $request->get('file');
if($src) {
$filePath = $src('file')->store('gea', 'azure');
}else{
$filePath = "";
}
return response()->json([
'success'=>"Success",
'file' => $src
]);
}
everytime I try to save it I am getting this kind of error.
messag: "Call to undefined function blob:http://127.0.0.1:8000/cccabc59-e35f-46f9-8e9a-fb2fd11b811b()"
Please anyone help me on how to do this right.

Related

Save generated PDF file on the server with jsPDF and PHP

I'm trying to save the generated PDF file with JSPDF plugin into the server instead of being saved on the client side, the javascript part that handles the JsPDF is this:
<script type="text/javascript">
(function(){
var
form = $('.form'),
cache_width = form.width(),
//cache_height = form.height(),
a4 =[ 595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
var imgWidth = 220;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
processData: false,
contentType: false,
success: function(response){
alert(response);
console.log(response)
},
error: function(err){
alert(err);
console.log(err)
}
});
});
}
// create canvas object
function getCanvas(){
form.width((a4[0]*1.33333) -80).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
</script>
the upload.php file should move the generated pdf file or its content to the Uploads folder but it seems that the $_FILES['data'] is empty
<?php
if(!empty($_FILES['data'])) {
// PDF is located at $_FILES['data']['tmp_name']
$content = file_get_contents($_FILES['data']['tmp_name']);
//echo $content;
$location = "uploads/";
move_uploaded_file($_FILES['data']['tmp_name'], $location.'random-name.pdf');
} else {
throw new Exception("no data");
}
the response I get back from Ajax is "Notice: Undefined index: data ".
Thanks in advance for any help.
I finally got it to work using this code:
var pdf = btoa(doc.output());
var file_name = $('#id').val();
//var file_name = 'hello world';
$.ajax({
method: "POST",
url: "upload.php",
data: {data: pdf, filename: file_name},
}).done(function(data){
// alert(data);
console.log(data);
});
and on the server side upload.php like this:
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
$fileName = $_POST['filename'];
file_put_contents( "uploads/".$fileName.".pdf", $data );
} else {
echo "No Data Sent";
}
exit();

Passing input file type via ajax to php is not working

I have this function to get values from a form
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();
$.ajax({
url:"fetch_import.php",
method:"POST",
data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
and a php code like this:
enter code here$bcid = $_POST['batchid'];
$yrs = $_POST['yrstart'];
$yrg = $_POST['yrend'];
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);
passing the file doesn't work. I've searched for this but still not working for me, i think i'll understand how it will work. Any idea? Tyia
You should append your fields to fd and simply use that as data-parameter in $.ajax:
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
fd.append('batchid', $("input[name='batchid']").val());
fd.append('yrstart', $("input[name='yrstart']").val());
fd.append('yrend', $("input[name='yrend']").val());
$.ajax({
url:"fetch_import.php",
method:"POST",
data: fd,
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});

Phonegap to Laravel image upload is blank/white

Phonegap is telling success, Laravel is telling me success but it's always white.
Phonegap (Android) two relevant code blocks of js are:
function sendImage(src) {
window.localStorage.setItem('csrf', csrf);
src = (src == 'library') ? Camera.PictureSourceType.PHOTOLIBRARY : Camera.PictureSourceType.CAMERA;
navigator.camera.getPicture(success, fail, {quality: 45, sourceType: src});
function success(imageData) {
imageData = getBase64Image(imageData);
userId = window.localStorage.getItem("user_id");
var url = 'https://example.com/profile/update/picture';
var params = {photo: 'image/png;space,' + imageData, user_id: userId};
//csrf = window.localStorage.getItem("csrf");
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: params,
headers: {"x-csrf-token": 'notoken'},
async: false,
success: function(res)
{
if(res.success)
{
alert("Success!");
}
},
complete: function(res)
{
},
error: function(res)
{
alert("Error = " + JSON.stringify(res));
}
});
}
function fail(error){
alert('You are FAIL');
}
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
//use this block to not draw image unless image is loaded
var callback = function(image) {
if(!image) image = this;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(image, 0, 0);
}
//check if image is loaded
if(img.complete) {
callback(img);
}else {
img.onload = callback;
}
//get the data-URL formatted image
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
}
In Laravel the photo is updating to blank or empty. At one point I have this code block in there that was returning true so Laravel at least thinks that image is legit:
public static function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
If you obtain blank or transparent image which means your drawing function called before image totally uploaded. Javascript works asynchron. In your code below two lines executed before your callback() function executed.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

Upload Image and insert in Database MySQl withAjax

i m user JQuery mobile and PHP and Ajax to upload Image and insert it in Database,but i have a probleme in insert the name of image in a database,the result in database is :"C:fakepathLighthouse.jpg",i would insert just the name of image after upload it.
Mu code in php
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
£fichier=basename($file['name'];
$uploaddir = 'photo/';
foreach($_FILES as $file)
{if(move_uploaded_file($file['tmp_name'], $uploaddir. $fichier)))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
my code script:
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
console.log('nom de l image:' + '&filenames[]=' + value);
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
my initial page(index.html)
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var latt = position.coords.latitude;
var lngg = position.coords.longitude;
var nom=$('input[id=nom]').val();
var photo= $('input[id=file_upload]').val();
var ville= $('input[id=ville]').val();
var pays= $('input[id=pays]').val();
long.value="Longitude: " + lngg;
lat.value="Latitude: " + latt;
//var adr="Sousse";
codeLatLng(latt, lngg);
// var adresse=codeLatLng(latt, lngg);
var sendAjax = $.ajax({
type: "POST",
url: 'api.php?rquest=insertMosque',
data: 'lat='+latt+'&lng='+lngg+'&nom='+nom+'&pays='+pays+'&ville='+ville+'&photo='+photo,
success: handleResponse
});
function handleResponse(){
$('#answer').get(0).innerHTML = sendAjax.responseText;
//console.log(data);
}
}
function errorFunction(){
alert("Geocoder failed");
}
}
code api.php
private function insertMosque() {
if ($this->get_request_method() != "POST") {
$this->response('', 406);
}
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
$photo=$_POST['photo'];
//$photo = addslashes($file['name']);
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
if ($query) {
$data['success'] = 'Insertion avec success';
} else {
$data['errors'] = 'failed';
}
$this->response($this->json($data), 200);
}
You could use the explode function in your api.php to parse the filepath you are getting from POST:
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
//for example, say $_POST['photo'] = "C:/my/fake/directory/testfile.jpg"
$photopath = explode("/", $_POST['photo']);
//print_r($photopath) results in Array ( [0] => C: [1] => my [2] => fake [3] => directory [4] => testfile.jpg )
$photo = end($photopath); //gets last result in the array (your filename)
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
Please note that this may not be the most efficient method of getting the filename from a path, and your delimiter ("/" in the example above) might need to change based on how you are getting your path. If you have any questions feel free to ask.

submit form data and files using phonegap?

I have created simple html form that contains text inputs, text area , files such as uploading images ..
how could I submit this form data when turning it into phone gap application that contains user registration to his data and photo and cv document?
when submitting data it should be sent to php page where mysql insert will held?
I have tried the serialize method face problems in getting data in th php page
also couldn't find the way to upload file and images??
any help???
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("Hello ");
$("#button").click(function(evt){
var name = $("#name").val();
var message = $("#message").val();
var sendData = { "name": name, "message": message };
$.ajax({
type: "POST",
url: "http://localhost/webs/main/ajax/process.php",
data: sendData,
success: function(data) {
log.console(data);
$("#info").html(data);
}
});
alert("Hello ");
alert($("#test").val());
alert($("#name").val());
alert($("#message").val());
return false;
});
}
Upload image using phonegap
============================
function uploadImage(){
//Using Camera
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#vImage').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
On your php file
=================
file_put_contents("file.txt", print_r($_FILES, true));
Post Form data and Image together
================================
// Here first submit your form input data after successfully submit upload image call
$('#submit').on('click', function(event){
if(event.handled !== true)
{
var ajax_call = serviceURL;
var str = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
$.each(response, function(key, value) {
// after success submit data
if(response){
var imagefile = $('#vImage').attr('src');
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.mimeType="image/png";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
});
}
});
event.handled = true;
}
return false;
})

Categories