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";
}
Related
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');
};
?>
I have a variables src and image,
var src = $("#img_tag").attr('src');
var image = new Image();
I want to pass this image variable to a public function in php to upload. What is it that exactly that I need to pass, is it the src, the base64, the image itself as new FormData ?
Right now I have:
var data = new FormData();
var src = $("#img_tag").attr('src');
var image = new Image();
data.append('Image', image);
console.log(data);
$.ajax({
url: "/products/image_upload",
type: "POST",
data: data,
processData: false,
contentType: false,
success: function (msg) {
console.log(msg+"---Image was uploaded");
}
error: function(err) {
console.log(err);
}
});
In my view:
public function image_upload() {
$this->autoRender = false;
echo json_encode($this->data);
if($this->request->is('post'))
{
if(!empty($_FILES['Image']['name'])) {
$file = $_FILES['Image'];
echo json_encode($file);
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif', 'png');
$temp = explode(".", $file['name']);
$newfilename = $_FILES['Image']['name'];
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/product-uploads' . DS . $newfilename))
{
echo json_encode("Image uploaded properly");
return json_encode($_FILES);
}
}
}
}
}
And getting:
{"Image":"[object HTMLImageElement]"}---Image was uploaded
BUT IMAGE IS NOT UPLOADED
If you take a look at the FormData.append doc, you will see that the second argument takes a string or a blob.
So passing an HTMLImageElement isn't going to work, if you cant get the image as a Blob or a File using a FormData object doesn't really help.
Since you're trying to upload the src of #img_tag, this will only really work if it is the base64 encoded image.
In this case use data.append('Image', src); and read the data from $_POST['Image'] then clean it up and decode it.
If the image src is a regular url, use $_POST['Image'] with curl to download the image to your server.
I got a bit of a research, and found this article super helpful. (Thanks to that)
I managed to upload an image file to a directory in my server from an image src by getting the base64 encoded image, passed for the controller to decode and upload. (Also thanks to Musa, DanielO, and Rory McCrossan)
In Controller: Code from this article. (I added a custom filename in a datetime format)
public function additional_image_upload() {
$this->autoRender = false;
$base64 = $this->request->data['base64'];
$product_id = $this->request->data['id'];
$baseFromJavascript = $base64;
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $baseFromJavascript));
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$date_tmp = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
$date = $date_tmp->format("Y-m-d_his.u");
$filepath = WWW_ROOT . 'img/product-uploads' . DS ."$date.jpg"; // or image.jpg
file_put_contents($filepath,$data);
}
In Script: (I passed the base64 encoded image for the controller to handle)
var src = $(this).attr('src');
$.ajax({
url:"/products/additional_image_upload",
data:{
"id": "<?= $id; ?>",
"base64": src
},
type:"POST",
success: function(msg) {
console.log(msg."---Img uploaded");
},
error: function(error) {
console.log(error);
}
});
And all was working great. Added this to help future readers.
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);
?>
I have a page in which I'm uploading an image using from input type=file to an image tag using this code
$('#profile-image-upload').change( function(event) {
var path = URL.createObjectURL(event.target.files[0]);
$("#image").attr('src',URL.createObjectURL(event.target.files[0]));
This gives me an bolb data of path like this blob:http://localhost:8080/467d02c9-0af0-448a-a239-69e8d4037dd1. My image is in this blob data saved in path variable
Now I also want this image file to save in my server directory and I'm use ajax to send it to my server
var ajax;
if (window.XMLHttpRequest) // For modren Browsers
ajax=new XMLHttpRequest();
else
ajax=new ActiveXObject("Microsoft.XMLHTTP"); // For IE5 & IE8
ajax.open("POST","../UploadImg.php",true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data= "path="+path+"&type="+user+"&id="+id+"&extent="+extent;
//path = blob data
//user = user name
//id = user id
//extent = extension of image
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200){
alert(ajax.responseText);
}
}
ajax.send(data);
});
and my server side coding is
$img_ff = $_POST["path"]; // blob path
$user = $_POST["type"];
$id = $_POST["id"];
$extension = $_POST["extent"];
$dst_img= $user.$id.".".$extention; // for example user17.png
$dst_path= "localhost:8080/live4others/images/";
$dst_cpl = $dst_path . $dst_img;
if(move_uploaded_file($dst_cpl, $img_ff)){
echo "yes";
}else{
echo "error";
}
if( file_put_contents( $img_ff, $dst_cpl)){
echo "yes";
}else{
echo "error";
}
both of the methods are not working. Please tell me where I'm doing wrong. They give error and says given path is invalid.
You can try this. I'm using same but using blob to simply preview the images/videos before submitting.
Jquery
$('#<formId>').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "../UploadImg.php",
type: "POST",
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData:false,
success: function(response){
console.log(response);
},
error : function (jqXHR, textStatus, errorThrown) {
}
});
});
PHP - UploadImg.php
$tmpFile = $_FILES['<fileElementName>'];
$absolutePathOfdestinationFolder = '/var/www/<projectDocRoot>/images/'.$user.$id.".".$extention;
if(move_uploaded_file($tmpFile['tmp_name'], $absolutePathOfdestinationFolder)){
echo "yes";
}else{
echo "error";
}
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?.