html2pdf: downloading pdf texts are overlapping and break the page - javascript

Currently, I am using the html2pdf library for downloading PDF files, it is working fine for me, but the problem is that after a few downloads the texts are overlapping and the complete page is broken. Using a pagebreak class I can restrict the page break issue but the overlapping issue and the broken page issue is still there. tried codes are
<div class="export-pdf" id="export-pdf">
<div class="fullWidth page-min-height">
Planned Procedure
</div>
</div>
var element = document.getElementById('export-pdf');
var opt = {
margin: [10, 0, 10, 0],
pageNumber: true,
pagebreak: {
mode: 'css',
avoid: '.breakPage',
before: '.beforeClass'
},
filename: test.pdf,
};
html2pdf().set(opt).from(element).save()
texts are overlapped I am expecting 'Planned Procedure'...if we have more data
complete pdf text become overlap after a few downloads,

Try This function
function genTablePDF(heightSize){
html2canvas(document.getElementById("HTMLtoPDF"),{
onrendered: function (canvas){
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',5,8,200, +heightSize);
doc.setPage(2);
doc.internal.getNumberOfPages();
var dateName = new Date();
doc.save('PDF ( ' + dateName + ' ) ' +'.pdf'); // file name pdf
}
});
}
in last parameter the variable is for height of the page
doc.addImage(img,'JPEG',5,8,200, +heightSize);
You can pass it through function heightSize OR you can use
heightSize = document.getElementById('pageSize').value
where document.getElementById('pageSize').value is giving the numbers of rows the the page table have or you can use your business logic like:
var heightSize = document.getElementById('pageSize').value;
if( +heightSize === 7 ){
heightSize = 120;
}
if( +heightSize === 14 ){
heightSize = 200;
}
if( +heightSize === 21 ){
heightSize = 260;
}
if( +heightSize === 28 || +heightSize === 35 || +heightSize === 42 || +heightSize === 50 ){
heightSize = 285;
}
doc.addImage(img,'JPEG',5,8,200, +heightSize);
I hope it is helpful for you :)

var element = document.getElementById('inner');
var opt = {
margin: 30,
filename: this.auth_user,
image: {type: 'jpeg',quality: 0.98},
html2canvas: {
scale: 2,
bottom: 20
},
pagebreak: { mode: ['css'], padding : 200 },
jsPDF: {
unit: 'mm',
orientation: 'portrait'
}
};
html2pdf().set(opt).from(element).then(function() {
}).save();

Had also problems with overlapping text with safari browser. This fix helped: GitHub. "remove linebreaks from tags"

Related

Pass javascript variable data to MySQL database in this situation

I have followed a codepen project to build an animated form. May I know how can I store the answer to my SQL database? The answers are stored in the questions array with the key answer but I am not sure how to extract them. Thanks!
var questions = [
{question:"What's your first name?"},
{question:"What's your last name?"},
{question:"What's your email?", pattern: /^[^\s#]+#[^\s#]+\.[^\s#]+$/},
{question:"Create your password", type: "password"}
]
var onComplete = function() {
var h1 = document.createElement('h1')
h1.appendChild(document.createTextNode('Thanks ' + questions[0].answer + ' for checking this pen out!'))
setTimeout(function() {
register.parentElement.appendChild(h1)
setTimeout(function() { h1.style.opacity = 1 }, 50)
}, 1000)
}
;(function(questions, onComplete) {
var tTime = 100 // transition transform time from #register in ms
var wTime = 200 // transition width time from #register in ms
var eTime = 1000 // transition width time from inputLabel in ms
if (questions.length == 0) return
var position = 0
putQuestion()
forwardButton.addEventListener('click', validate)
inputField.addEventListener('keyup', function(e) {
transform(0, 0) // ie hack to redraw
if (e.keyCode == 13) validate()
})
previousButton.addEventListener('click', function(e) {
if (position === 0) return
position -= 1
hideCurrent(putQuestion)
})
function putQuestion() {
inputLabel.innerHTML = questions[position].question
inputField.type = questions[position].type || 'text'
inputField.value = questions[position].answer || ''
inputField.focus()
progress.style.width = position * 100 / questions.length + '%'
previousButton.className = position ? 'ion-android-arrow-back' : 'ion-person'
showCurrent()
}
}(questions, onComplete))
In order for it to work you need jquery support for your website
Try doing following:
Assume you are storing your variables in JS array like
var numbers = [45, 4, 9, 16, 25];
You can try using built-in JS funtion to cycle through the array like:
numbers.forEach(myFunction);
You define your function that you use in point 2, with ajax, smth like
myFunction(value){
// answers is used to indicate to your server side script type of operation to be performed to be use in isset(), as value is too general`
var datastring = 'answers' + '&value=' + value;
// in URL indicate path to your actual server side script that will put records in database
ajax({
type: "POST",
url: "/app/server.php",
data: datastring,
success: function (html) {
console.log(html);
}
}); //End of Ajax
return false;
}

html2pdf.js produces a blank document on iOS

I am using eKoopman's html2pdf.js library https://github.com/eKoopmans/html2pdf.js to produce a list of recommendation for a user at the end of an assessment. These are dynamically generate based on the responses.
It works wonderfully on desktop. However when I try to output the PDF on iOS the document is blank except for the headers and footers that I add in a separate function.
Its like it completely ignores the element.
Below is the code I trigger when the user clicks a button.
var element = $('#recommendationsdisplay').html();
var opt = {
margin: [.75,0,.75,0],
filename: 'Click_Start_' + Math.floor(Date.now() / 10000) + '.pdf',
enableLinks: true,
image: {
type: 'jpeg',
quality: 1
},
html2canvas: {
scale: 2,
dpi: 300,
letterRendering: true
},
jsPDF: {
unit: 'in',
format: 'letter',
orientation: 'portrait'
},
pagebreak:{
mode: ['avoid-all', 'css', 'legacy'],
avoid: 'div.recgrid-item'
}
};
html2pdf().from(element, 'string').set(opt).toPdf().get('pdf').then(function (pdfObject) {
/* some image related encoding */
var headerTitle = "Recommendations";
var footerCR = "© 2020";
// Header and Footer
for (var i = 1; i < pdf_pages.length; i++) {
pdfObject.setPage(i);
pdfObject.setFontSize(14);
pdfObject.setTextColor('#0090DA');
pdfObject.addImage(headerData, 'PNG', 0, 0, 8.5, .5);
pdfObject.setFontSize(10);
pdfObject.setTextColor('#777777');
pdfObject.text(footerCR, 4, 10.5);
pdfObject.text(' ' + i, 7.375, 10.5);
pdfObject.addImage(logoData, 'PNG', .75, 10.25, 1, .325);
}
}).save();
EDIT: It seems like the issue is with the canvas size limitation. The element is rendered properly in the PDF if its height is NOT above a certain threshold (fewer items chosen in the assessment). My document is only a few pages long (<7)though and I have seen other users report being able to create PDFs with dozens of pages so I am not sure what the issue is.
pagebreak mode = avoid-all causing the problem. Take away 'avoid-all' .
I have resolved this issue by splitting the whole document into pages and then passing pages one by one to the html2pdf library to generate and bind all pages into a single pdf file.
Example code.
var opt = {
margin: [5, 10, 0.25, 10],
pagebreak: {mode: 'css', after: '.page2el'},
image: {type: 'jpeg', quality: 1},
filename: 'testfile.pdf',
html2canvas: {dpi: 75, scale: 2, letterRendering: true},
jsPDF: {unit: 'pt', format: 'letter', orientation: 'p'},
};
var count = 1;
let doc = html2pdf().set(opt).from(document.getElementById('page2el')).toPdf();
jQuery("#cs_pdf").find("div").each(function (e) {
// Filtering document each page with starting id with page2el
if (jQuery(this).attr('id') && jQuery(this).attr('id').indexOf('page2el') != -1) {
if (count != 1) {
doc = doc.get('pdf').then((pdf) => {
pdf.addPage();
var totalPages = jQuery("#cs_pdf").find(".page2el").length + 1;
// Adding footer text and page number for each PDF page
for (let i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(10);
pdf.setTextColor(60);
if (i !== 1) {
pdf.text('Page ' + i + ' of ' + totalPages, pdf.internal.pageSize.getWidth() - 100, pdf.internal.pageSize.getHeight() - 25);
}
if (i === 1) {
pdf.text("Confidential", pdf.internal.pageSize.getWidth() - 340, pdf.internal.pageSize.getHeight() - 35);
} else {
pdf.text(consultant_company, pdf.internal.pageSize.getWidth() - 530, pdf.internal.pageSize.getHeight() - 25);
}
}
}).from(document.getElementById(jQuery(this).attr('id'))).toContainer().toCanvas().toPdf();
}
count++;
}
// On Jquery each loop completion executing save function on doc object to compile and download PDF file
}).promise().done(function () {
doc.save();
});

Image is chopped while generating PDF from PieCharts (Amchart)

I want to export my pie chart as pdf , everything is fine when results are limited to 5-6, after that image is chopping in PDF See the image below
Chopped Image in PDF
The Problem I am getting is because we are using Scrollbar if result is large See the image below
Generating Pie Charts.Due to this scroll bar we are not able to capture the image of the report hence we are getting the chopped image. Can anyone help me with this issue. Below is the code we are using for generating pdf from piecharts
// Collect actual chart objects out of the AmCharts.charts array
var ids = ["chartdiv-" +data.id];
var charts = {}
var charts_remaining = ids.length;
for (var i = 0; i < ids.length; i++) {
for (var x = 0; x < AmCharts.charts.length; x++) {
if(!(charts[ids[i]])){
if (AmCharts.charts[x].div.id == ids[i])
if(this.criteria.fullView && AmCharts.charts[x].container.height > 290 && AmCharts.charts[x].container.height != 330 && document.body.contains(AmCharts.charts[x].containerDiv))
charts[ids[i]] = AmCharts.charts[x];
else if(AmCharts.charts[x].container.height == 330 && this.criteria.dashBoard && document.body.contains(AmCharts.charts[x].containerDiv))
charts[ids[i]] = AmCharts.charts[x];
else if(!this.criteria.fullView && !this.criteria.dashBoard && AmCharts.charts[x].container.height > 290 && document.body.contains(AmCharts.charts[x].containerDiv))
charts[ids[i]] = AmCharts.charts[x];
}
}
}
// Trigger export of each chart
for (var x in charts) {
if (charts.hasOwnProperty(x)) {
var chart = charts[x];
chart.export.capture({}, function() {
this.toJPG({ multiplier: 2 }, function(data) {
// Save chart data into chart object itself
this.setup.chart.exportedImage = data;
// Reduce the remaining counter
charts_remaining--;
// Check if we got all of the charts
if (charts_remaining == 0) {
// Yup, we got all of them
// Let's proceed to putting PDF together
generatePDF();
}
});
});
}
}
function generatePDF() {
var id = divId;
var layout = {
"content": []
}
layout.content.push(
{"text": name, "fontSize": 13, "fit": [ 523.28, 769.89 ]},
{
"image": charts["chartdiv-"+id].exportedImage,
"width" : 40,
"fit": fitParam
}, { "text": content, "fontSize": 10});
chart["export"].toPDF(layout, function(data) {
this.download(data, "application/pdf", "amCharts.pdf");
});
}
};

Issue creating pdf with tables in IE

Currently, I'm using jspdf latest version and jspdf-AutoTable 2.1.0 latest version in order to create a PDF with a very complicated table.
It works like a charm in Chrome and FireFox (big surprise!) but in IE10, it's rendering the pdf awfully (another big surprise!)
This is the output of one of the most extensive tables in pdf on chrome (Currently empty)
This is the pdf that IE10 renders
As you can see, it's not wrapping the column header as it should, nor it's expanding and showing the first columns cells and cropping the text inside them.
In order to mantain my custom table style, with it's content correct styling, I adjusted and created my own GetTableJSON method, so I can retrieve and store each individual cell style and apply it later on the createdHeaderCell and createdCell hooks
This is the complete code used in order to create this pdf with it's custom style
function DownloadSchedulePDF() {
var orientation = landscape ? 'l' : 'p'
var doc = new jsPDF(orientation, 'pt', paperFormat);
doc.text('Header', 40, 50);
var res = GetTableJSON($(".scheduleGrid table"));
tableCellsStyles = res.styles;
doc.autoTable(res.columns, res.data, {
theme: 'plain',
startY: 60,
pageBreak: 'auto',
margin: 20,
width: 'auto',
styles: {
lineWidth: 0.01,
lineColor: 0,
fillStyle: 'DF',
halign: 'center',
valign: 'middle',
columnWidth: 'auto',
overflow: 'linebreak'
},
createdHeaderCell: function (cell, data) {
ApplyCellStyle(cell, "th", data.column.dataKey);
},
createdCell: function (cell, data) {
ApplyCellStyle(cell, data.row.index, data.column.dataKey);
},
drawHeaderCell: function (cell, data) {
//ApplyCellStyle(cell, "th", data.column.dataKey);
//data.table.headerRow.cells[data.column.dataKey].styles = cell.styles;
//ApplyCellStyle(data.table.headerRow.cells[data.column.dataKey], "th", data.column.dataKey);
},
drawCell: function (cell, data) {
if (cell.raw === undefined)
return false;
if(cell.raw.indexOf("*") > -1) {
var text = cell.raw.split("*")[0];
var times = cell.raw.split("*")[1];
doc.rect(cell.x, cell.y, cell.width, cell.height * times, 'FD');
doc.autoTableText(text, cell.x + cell.width / 2, cell.y + cell.height * times / 2, {
halign: 'center',
valign: 'middle'
});
return false;
}
}
});
doc.save("schedule " + selectedDate.toLocaleDateString() + ".pdf");
}
function ApplyCellStyle(cell, x, y) {
if(!pdfInColor)
return;
var styles = tableCellsStyles[x + "-" + y];
if (styles === undefined)
return;
cell.styles.cellPadding = styles.cellPadding
cell.styles.fillColor = styles.fillColor;
cell.styles.textColor = styles.textColor;
cell.styles.font = styles.font;
cell.styles.fontStyle = styles.fontStyle;
}
Object.vals = function (o) {
return Object.values
? Object.values(o)
: Object.keys(o).map(function (k) { return o[k]; });
}
// direct copy of the plugin method adjusted in order to retrieve and store each cell style
function GetTableJSON (tableElem, includeHiddenElements) {
includeHiddenElements = includeHiddenElements || false;
var columns = {}, rows = [];
var cellsStyle = {};
var header = tableElem.rows[0];
for (var k = 0; k < header.cells.length; k++) {
var cell = header.cells[k];
var style = window.getComputedStyle(cell);
cellsStyle["th-" + k] = AdjustStyleProperties(style);
if (includeHiddenElements || style.display !== 'none') {
columns[k] = cell ? cell.textContent.trim() : '';
}
}
for (var i = 1; i < tableElem.rows.length; i++) {
var tableRow = tableElem.rows[i];
var style = window.getComputedStyle(tableRow);
if (includeHiddenElements || style.display !== 'none') {
var rowData = [];
for (var j in Object.keys(columns)) {
var cell = tableRow.cells[j];
style = window.getComputedStyle(cell);
if (includeHiddenElements || style.display !== 'none') {
var val = cell
? cell.hasChildNodes() && cell.childNodes[0].tagName !== undefined
? cell.childNodes[0].textContent + (cell.getAttribute("rowSpan") ? "*" + cell.getAttribute("rowSpan") : '')
: cell.textContent.trim()
: '';
cellsStyle[(i-1) + "-" + j] = cell
? cell.hasChildNodes() && cell.childNodes[0].tagName !== undefined
? AdjustStyleProperties(window.getComputedStyle(cell.childNodes[0]))
: AdjustStyleProperties(window.getComputedStyle(cell))
: {};
rowData.push(val);
}
}
rows.push(rowData);
}
}
return {columns: Object.vals(columns), rows: rows, data: rows, styles: cellsStyle}; // data prop deprecated
};
function AdjustStyleProperties(style) {
return {
cellPadding: parseInt(style.padding),
fontSize: parseInt(style.fontSize),
font: style.fontFamily, // helvetica, times, courier
lineColor: ConvertToRGB(style.borderColor),
lineWidth: parseInt(style.borderWidth) / 10,
fontStyle: style.fontStyle, // normal, bold, italic, bolditalic
overflow: 'linebreak', // visible, hidden, ellipsize or linebreak
fillColor: ConvertToRGB(style.backgroundColor),
textColor: ConvertToRGB(style.color),
halign: 'center', // left, center, right
valign: 'middle', // top, middle, bottom
fillStyle: 'DF', // 'S', 'F' or 'DF' (stroke, fill or fill then stroke)
rowHeight: parseInt(style.height),
columnWidth: parseInt(style.width) // 'auto', 'wrap' or a number
//columnWidth: 'auto'
};
}
function ConvertToRGB(value) {
if (value === undefined || value === '' || value === "transparent")
value = [255, 255, 255];
else if (value.indexOf("rgb") > -1)
value = value.replace(/[^\d,]/g, '').split(',').map(function (x) { return parseInt(x) });
else if (value.indexOf("#") > -1)
value = value.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
, function (m, r, g, b) { return '#' + r + r + g + g + b + b })
.substring(1).match(/.{2}/g)
.map(function (x) { return parseInt(x, 16) });
else if (Array.isArray(value))
return value;
else {
var canvas, context;
canvas = document.createElement('canvas');
canvas.height = 1;
canvas.width = 1;
context = canvas.getContext('2d');
context.fillStyle = 'rgba(0, 0, 0, 0)';
// We're reusing the canvas, so fill it with something predictable
context.clearRect(0, 0, 1, 1);
context.fillStyle = value;
context.fillRect(0, 0, 1, 1);
var imgData = context.getImageData(0, 0, 1, 1);
value = imgData.data.slice
? imgData.data.slice(0, 3)
: [imgData.data[0], imgData.data[1], imgData.data[2]];
}
return value;
}
Edit:
As requested, this is the table HTML and the JSON for the tableCellStyles variable
https://jsfiddle.net/6ewqnwty/
Due to the size of the table and the amount of characters for the HTML and the JSON, I set them in a separate fiddle.
Edit 2:
I just made the fiddle runnable, being able to reproduce the issue.
https://jsfiddle.net/6ewqnwty/1/
Not perfectly as I have it in my application, I'm able to retrieve the pdf with the styling, only missing the columns headers text, but at least the issue when downloading the pdf on IE is still present
Running your example I get NaN for cellPadding. This is also probably the reason it does not work with the latest version. You could do something simple such as adding:
cell.styles.cellPadding = styles.cellPadding || 5;
in ApplyCellStyle. The reason you get NaN is that IE apparantly returns empty string instead of '0px' which chrome etc does.
Also note that you would not need to parse the html table yourself if you upgrade since cell.raw is set to the html element in the latest version. This means that you could parse the style with something like window.getComputedStyle(cell.raw).

upload fails with image greater than 800kb

I have a form where i can drag and drop an image into a canvas and then click an upload button to upload the file to the server. Below is my javascript file and php file. I cannot find where or why this will not allow me to upload something greater than 800kb? I believe its all failing in the php at if(file_put_contents($uploaddir.$randomName, $decodedData)) { but again i dont know why? The sql statment fails to by the way thats why i think its failing at that point in the php file. 32M is php max file size upload.
UPDATE... i removed anything to do with uploading with php in the php and only left echo $randomName.":uploaded successfully"; which now leads me to believe there is something wrong in the JS file at $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { for anything greater than 800kb (ish)
JS
$(document).ready(function() {
// Makes sure the dataTransfer information is sent when we
// Drop the item in the drop box.
jQuery.event.props.push('dataTransfer');
var z = -40;
// The number of images to display
var maxFiles = 1;
var errMessage = 0;
// Get all of the data URIs and put them in an array
var dataArray = [];
// Bind the drop event to the dropzone.
$('#drop-files').bind('drop', function(e) {
// Stop the default action, which is to redirect the page
// To the dropped file
var files = e.dataTransfer.files;
// Show the upload holder
$('#uploaded-holder').show();
$('#drop-files').hide();
// For each file
$.each(files, function(index, file) {
// Some error messaging
if (!files[index].type.match('image.*')) {
if(errMessage == 0) {
$('#drop-files').html('Hey! Images only');
++errMessage
}
else if(errMessage == 1) {
$('#drop-files').html('Stop it! Images only!');
++errMessage
}
else if(errMessage == 2) {
$('#drop-files').html("Can't you read?! Images only!");
++errMessage
}
else if(errMessage == 3) {
$('#drop-files').html("Fine! Keep dropping non-images.");
errMessage = 0;
}
return false;
}
// Check length of the total image elements
if($('#dropped-files > .image').length < maxFiles) {
// Change position of the upload button so it is centered
var imageWidths = ((220 + (40 * $('#dropped-files > .image').length)) / 2) - 20;
$('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'});
}
// Start a new instance of FileReader
var fileReader = new FileReader();
// When the filereader loads initiate a function
fileReader.onload = (function(file) {
return function(e) {
// Push the data URI into an array
dataArray.push({name : file.name, value : this.result});
// Move each image 40 more pixels across
z = z+40;
var image = this.result;
// Just some grammatical adjustments
if(dataArray.length == 1) {
$('#upload-button span').html("1 file to be uploaded");
} else {
$('#upload-button span').html(dataArray.length+" files to be uploaded");
}
// Place extra files in a list
if($('#dropped-files > .image').length < maxFiles) {
// Place the image inside the dropzone
$('#dropped-files').append('<div class="image" style="background: #fff url('+image+') no-repeat;background-size: cover;background-position: center center;"> </div>');
}
else {
$('#extra-files .number').html('+'+($('#file-list li').length + 1));
// Show the extra files dialogue
$('#extra-files').show();
// Start adding the file name to the file list
$('#extra-files #file-list ul').append('<li>'+file.name+'</li>');
}
};
})(files[index]);
// For data URI purposes
fileReader.readAsDataURL(file);
});
});
function restartFiles() {
// This is to set the loading bar back to its default state
$('#loading-bar .loading-color').css({'width' : '0%'});
$('#loading').css({'display' : 'none'});
$('#loading-content').html(' ');
// --------------------------------------------------------
// We need to remove all the images and li elements as
// appropriate. We'll also make the upload button disappear
$('#upload-button').hide();
$('#dropped-files > .image').remove();
$('#extra-files #file-list li').remove();
$('#extra-files').hide();
$('#uploaded-holder').hide();
$('#drop-files').show();
// And finally, empty the array/set z to -40
dataArray.length = 0;
z = -40;
return false;
}
$('#upload-button .upload').click(function() {
$("#loading").show();
var totalPercent = 100 / dataArray.length;
var x = 0;
var y = 0;
$('#loading-content').html('Uploading '+dataArray[0].name);
$.each(dataArray, function(index, file) {
bla = $('#gpID').val();
$.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) {
var fileName = dataArray[index].name;
++x;
// Change the bar to represent how much has loaded
$('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'});
if(totalPercent*(x) == 100) {
// Show the upload is complete
$('#loading-content').html('Uploading Complete!');
// Reset everything when the loading is completed
setTimeout(restartFiles, 500);
} else if(totalPercent*(x) < 100) {
// Show that the files are uploading
$('#loading-content').html('Uploading '+fileName);
}
// Show a message showing the file URL.
var dataSplit = data.split(':');
if(dataSplit[1] == 'uploaded successfully') {
alert('Upload Was Successfull');
var realData = '<li>'+fileName+' '+dataSplit[1]+'</li>';
$('#drop-files').css({
'background' :'url(/mods/photogallery/photos/' + dataSplit[0] + ') no-repeat',
'background-size': 'cover',
'background-position' : 'center center'
});
$('#uploaded-files').append('<li>'+fileName+' '+dataSplit[1]+'</li>');
// Add things to local storage
if(window.localStorage.length == 0) {
y = 0;
} else {
y = window.localStorage.length;
}
window.localStorage.setItem(y, realData);
} else {
$('#uploaded-files').append('<li><a href="/mods/photogallery/photos/'+data+'. File Name: '+dataArray[index].name+'</li>');
}
});
});
return false;
});
// Just some styling for the drop file container.
$('#drop-files').bind('dragenter', function() {
$(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #bb2b2b'});
return false;
});
$('#drop-files').bind('drop', function() {
$(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'});
return false;
});
// For the file list
$('#extra-files .number').toggle(function() {
$('#file-list').show();
}, function() {
$('#file-list').hide();
});
$('#dropped-files #upload-button .delete').click(restartFiles);
// Append the localstorage the the uploaded files section
if(window.localStorage.length > 0) {
$('#uploaded-files').show();
for (var t = 0; t < window.localStorage.length; t++) {
var key = window.localStorage.key(t);
var value = window.localStorage[key];
// Append the list items
if(value != undefined || value != '') {
$('#uploaded-files').append(value);
}
}
} else {
$('#uploaded-files').hide();
}
});
PHP
// We're putting all our files in a directory.
$uploaddir = '../photos/';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
$gpID = $_GET['gpID'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
// You can use the name given, or create a random name.
// We will create a random name!
$randomName = $gpID.'.'.$mime;
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
$sql = "UPDATE zmods_galleriesphotos SET gpFile = '$randomName' WHERE gpID = '$gpID'";
$rows = $db->query($sql);
echo $randomName.":uploaded successfully";
}
else {
echo "Something went wrong. Check that the file isn't corrupted";
}
Check the upload_max_filesize in your php.ini file (although it should be large enough by default)
Check the post_max_size as well
If you're uploading multiple files, then also check max_file_uploads
The fact that your sql is failing makes me wonder if this is a mysql problem and not a php problem. What is the SQL error that occurs?

Categories

Resources