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();
Related
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.
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();
}
});
});
I am trying to send an image via JavaScript after displaying the preview on the screen, I refuse to use Dropzone, Plupload or any JavaScript library, because I just want a simple functionality.
var finput;
var fileReader;
var fd; //formdata...
$(function(){
fileReader = new FileReader;
fileReader.onload = function(e) {
var img = document.createElement("img");
img.src = fileReader.result; //display the image on the screen...
img.height = 200;
$('#pimgbox').html(img);
//enable the image button... // $('#pimagebox').html(img);
$('#pimgbtn').removeAttr('disabled', 'disabled').removeClass('btn-alert').addClass('btn-primary');
}
});
and when you click on the submit button
$('#pimgbtn').bind('click', function(e){
//initialize the formdata...
fd = new FormData(); //initialize the formdata..
fd.append('pimgupl', finput.files[0]); //s
//alert(fd);
$('#pimgldr').css('display','block');
$(this).attr('disabled', 'disabled').removeClass('btn-primary').addClass('btn-alert')
if(fileReader.result != null){
////////////// beginning of ajax call...
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
}; //end of setting..
$.ajax(settings)
.done(function (response) {
alert(response);
resetPUplButtons();
//close modal...
$('#profimgwin').modal('hide');
})
.fail(function (jqXHR, textStatus, error) {
alert('error sending file...' + error);
resetPUplButtons();
});
/////////////////////////end of ajax calls..
}else{
alert('you havent selected an image yet..');
resetPUplButtons();
}
});
and on my Laravel usercontroller I have this method that tries to upload the image but it's refusing to work.
public function setProfilePix(Request $request){
$file = $request->file('pimgupl');
$code = Auth::user()->profile->usrcode;
$targetDir = public_path() . DS . 'userdata'.DS.'ppix';
$newname = $targetDir.DS.strtolower($code).md5($code).'_'.time() .'.jpg';
// echo $newname;
//exit;
$file->move($targetDir, $newname);
echo 'saved';
}
I keep getting this error in my output panel:
Line 418 is the ajax operation, I have tried everything but nothing seems to be working. I have also added an exception to the route in my verifyCsrfToken.php - middleware, but still it isn't working.
In your jQuery try changing settings from
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
};
to
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd,
processData: false,
contentType: false,
};
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;
})
I am creating an AJAX PHP upload script, but I am having troubles. After the user selects an image to upload, it will show in the div container that I specified in the javascript file (good). But, the moving the uploaded file does not seem to work, or at least I think that is what the problem is. I set the uploads/ folder to have permission of "777".
Here is the JS file:
$(document).ready(function () {
$("#upload-image-button").hide();
var input = document.getElementById("images"),
formdata = false;
function showUploadedItem(source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
$("#topic-img-container").html(img);
}
if (window.FormData) {
formdata = new FormData();
$("#upload-image-button").hide();
}
$("input[type='file']").live("change", function(event) {
$("#response").html("Uploading...");
var i = 0, len = this.files.length, img, reader, file;
for (; i < len; i++) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "db/upload_image.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
});
Here is the PHP file:
<?php
foreach($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
print_r($_FILES);
$name = $_FILES["images"]["name"][$key];
move_uploaded_file($FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES["images"]["name"][$key]);
echo $FILES["images"]["tmp_name"][$key];
}
}
echo "Success";
?>
It gets into the loop when there is no error. When I go to the upload folder, there are no new files. Any idea why this might be?
You cannot upload files using AJAX. You need a helper Iframe that you send via a regular form-post.