Impossible save PDF to server with jsPDF - javascript

I'm newbie here and with javascript & php.
I can't save my PDF's with jsPDF to local storage on server (automatically generated). In the past works, but now I just put Canvas (javascript) into my HTML, and it doesn't work.
Any help is welcome :)
It works with doc.save javascript, but is not saving automatically to local.
Javascript:
let doc = new jsPDF('p', 'pt', 'a4');
doc.addHTML(document.body, function () {
//this works but not store in local automatically
// doc.save('test.pdf');
//store to local storage
var pdf = btoa(doc.output());
$.ajax({
method: "POST",
url: "pdftoserver.php",
data: {data: pdf},
}).done(function(data){
console.log(data);
});
});
}
PHP:
<?php
session_start();
$pdfpath=$_SESSION['pdfpath']; //heredated, only path and name for pdf (with date...)
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
// print_r($data);
file_put_contents($pdfpath, $data );
} else {
echo "PDF failed";
}
exit();
?>
MY HTML head scripts:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script src="canvas.js"></script> <!--for paint and sign on html-->

This works for me, Put this after your doc.save() or pdf.save()
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax({
url: 'upload.php',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response){console.log(response)},
error: function(err){console.log(err)}
});
Then create a upload.php with this:
<?php
$pdf = $_FILES['pdf']['tmp_name'];
$name = $_GET['name'];
if(isset($pdf)){
$location = "../uploads/";
move_uploaded_file($pdf, $location.$name.'.pdf');
};
?>

Related

JSPDF .output Image + txt

So i have a jspdf script im working with.
.save works as expected and outputs the image + text elements.
How ever
doc.output() = only text
doc.output('datauristring') = corrupted pdf
I think im missing something
here is an example of my code
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQIAdgB2AAD/examplestringonly...';
var doc = new jsPDF('p', 'pt');
doc.text(35, 340, "data notes");
doc.addImage(imgData, 'JPEG', 350, 40, 200, 40);
doc.output('datauristring');
Solved hope this helps anyone.
.output() was correctly sending all the date, how ever the base64 was being corrupted. so i made the php handle the datauri, and used base64_decode() on it.
then made it save to file.
fixes the issues completely.
var pdf = doc.output('datauri');
var data = new FormData();
data.append("data" , pdf);
data.append("id" , id);
$.ajax({
url: 'upload.php',
data: data,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
console.log('Exit to send request');
},
error: function (jqXHR) {
console.log('Failure to send request');
}
});
<?php
if(!empty($_POST['data'])){
$data = str_replace(' ','+',$_POST['data']);
$data = substr($imgData,strpos($imgData,",")+1);
$data = base64_decode($imgData);
$id = $_POST['id'];
$fname = "test.pdf"; // name the file
$file = fopen("api/warranty/pdf/" .$id, 'w'); // open the file path
fwrite($file, $data); //save data
fclose($file);
} else {
echo "No Data Sent";
}

jQuery AJAX - send file and variable to PHP in single request

I have the following HTML form for uploading a file (picture):
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
I use the following JavaScript/jQuery to send form data and a variable value to PHP script:
var variable1= 1;
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: {form_data, number: variable1},
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
The PHP script (upload.php) looks like this:
$filename;
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$filename = $_FILES['file']['name'];
}
echo $filename;
When I run this code, PHP throws some undefined index errors. If I use only "data: form_data" in ajax request (without variable1), then the file uploads successfully, but I need to send the variable too. How can I do this?
You can also append the number key => value to to the form data as
form_data.append('number', variable1);
Then in Ajax call
data: form_data,
why don't you append this value like this
form_data.append('number', variable1);
Append the variable to form_data
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('number', variable1); // append variable
In ajax
processData: false,
data: form_data, // data
type: 'post',
I am following your code because I need FILES image data and multiple variables in PHP script for insertion operation in the database. But I am unable to access any single variable in the php script. I did below to access your number variable. Please correct me.
//upload.php
if(isset($_GET['number'])){
$num = $_GET['number'];
echo $num;
}else{
echo 'not set';
}

File uploade with additional Data (Javascript, PHP)

I want to uploade a file and send additional data (an array) to the php script.
Here is the HTML and the Javascript Code:
<input type="file" name="fileinput" id="fileinput">
<button class="btn btn-primary" id="btnupload">upload</button>
<script>
$('#btnupload').click(function(){
var formData = new FormData();
formData.append("MacsToChangeImage", selectedMACs.toString()); //selectedMACs is the array which i want to send
formData.append("userfile", $('#fileinput').files[0]);
$.ajax({
url: "ChangeImagesFunction.php",
type:'POST',
data: formData,
processData: false,
cententType: false,
success: function(data)
{
alert('success' + data);
},
error:function(response){
alert(JSON.stringify(response));
}
});
});
</script>
And here ist the PHP Code:
if(!empty($_FILES)) {
$target_dir = "img/epd_uploads/";
$temporaryFile = $_FILES['userfile']['tmp_name'];
$targetFile = $target_dir . $_FILES['userfile']['name'];
if(!move_uploaded_file($temporaryFile,$targetFile)) {
echo "Error occurred while uploading the file to server!";
}else{
if (isset($_POST['MacsToChangeImage'])){
//Name of the Uploaded File
$ChangeImageToPHP = $_FILES['userfile']['name'];
//Get the Array
$MacsToChangeImageStr = $_POST['MacsToChangeImage'];
$MacsToChangeImagePHP = explode(",",$MacsToChangeImageStr);
}
}
}
I think the HTML and Javascript part is fine so far. But i am uncertain how to handle the PHP part. What am i doing worng/missing?
Are there other ways to achieve what im plannig to do?
Thank you in advance

How do I send images in an ajax request? [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$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' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

How to save my generated javascript pdf file to my server's filesystem?

I'm using pdfmake to create my pdf and while it allows the user to open the pdf directly or download it to their computer, I'm not sure how I would go about generating the pdf and saving it to my server's file system.
From what I understand, there are plenty of security measures not allowing javascript to save data to file(s), so would sending it to my php backend be the only choice ? and how would i go about doing that ?
Thanks !
(untested)
PHP:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
JS:
var docDefinition = {
content: 'This is an sample PDF printed with pdfMake'
};
pdfMake.createPdf(docDefinition).getBuffer(function(buffer) {
var blob = new Blob([buffer]);
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event) {
var fd = new FormData();
fd.append('fname', 'test.pdf');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php', // Change to PHP filename
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
});
Upload and receive code from How can javascript upload a blob?.

Categories