I'm using the jsPDF plugin to create a pdf file. Currently, the method can generate a download file based on the click button. instead of that, I would like to save the file into the server when I click the button. a few research I use jquery.ajax to send the data to the file server.
Code
PDFAnnotate.prototype.savePdf = function() {
var inst = this;
var doc = new jspdf.jsPDF();
inst.fabricObjects.forEach(function(fabricObj, index) {
if (index != 0) {
doc.addPage();
doc.setPage(index + 1);
}
doc.addImage(
fabricObj.toDataURL({
format: 'png'
}),
inst.pageImageCompression == "NONE" ? "PNG" : "JPEG",
0,
0,
doc.internal.pageSize.getWidth(),
doc.internal.pageSize.getHeight(),
`page-${index + 1}`,
["FAST", "MEDIUM", "SLOW"].indexOf(inst.pageImageCompression) >= 0 ?
inst.pageImageCompression :
undefined
);
if (index === inst.fabricObjects.length - 1) {
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', baseurl + "wo/replaceFile", true);
xhr.send('pdf');
}
})
}
Based on xhr.open I call method in controller Wo.php/replaceFile()
if(!empty($_FILES['pdf'])) {
$data = $_POST['pdf'];
$fname = "test.pdf"; // name the file
$file = fopen("testa/pdf/" .$fname, 'w');
fwrite($file, $data); //save data
fclose($file);
} else {
throw new Exception("no data");
}
?>
But no action happened.
Related
im doing a paste event from clipboard, it creates a blob url. Now i dont how to save or get the file. How can i save it to my computer? I think im totally wrong in getting the blob in my php. im getting it as a string then trying to save it
This is my code for creating the blob
<?php
if( isset( $_FILES['file'] ) ) {
$file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
header("Content-Type: " . $_FILES['file']['type'] );
die($file_contents);
}
else {
header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>
<script type="text/javascript">
document.onpaste = function (e) {
var items = e.clipboardData.items;
var files = [];
for( var i = 0, len = items.length; i < len; ++i ) {
var item = items[i];
if( item.kind === "file" ) {
submitFileForm(item.getAsFile(), "paste");
}
}
};
function submitFileForm(file, type) {
var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
var formData = new FormData();
formData.append('file', file, "image_file");
formData.append('extension', extension );
formData.append("mimetype", file.type );
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open('POST', '<?php echo basename(__FILE__); ?>');
xhr.onload = function () {
if (xhr.status == 200) {
var img = new Image();
img.src = (window.URL || window.webkitURL)
.createObjectURL( xhr.response );
document.getElementById("nye").appendChild(img);
document.getElementById("nye").style.display = "none" ;
var x = document.getElementById("image");
x.setAttribute("type", "text");
x.setAttribute("value", img.src);
document.getElementById("image").appendChild(x);
}
};
xhr.send(formData);
}
</script>
This is my code that's save to my computer, it runs but i juts recive a blank jpg file
<?php
$data = $_POST['url'];
$filePath = $uploadDir . $name;
$contents_split = explode(',', $data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$fp = fopen('sample23.jpg', 'w');
fwrite($fp, $decoded);
fclose($fp);
?>
it saves but i think the file is blank.
I'm working on a project to make sure that users finish a video. I would like to have it just add something like "user has finished video" to an already existing text file.
Here is what I have in my JavaScript file.
var video = document.getElementById("video");
var timeStarted = -1;
var timePlayed = 0;
var duration = 0;
// If video metadata is laoded get duration
if (video.readyState > 0)
getDuration.call(video);
//If metadata not loaded, use event to get it
else {
video.addEventListener('loadedmetadata', getDuration);
}
// remember time user started the video
function videoStartedPlaying() {
timeStarted = new Date().getTime() / 1000;
}
function videoStoppedPlaying(event) {
// Start time less then zero means stop event was fired vidout start event
if (timeStarted > 0) {
var playedFor = new Date().getTime() / 1000 - timeStarted;
timeStarted = -1;
// add the new ammount of seconds played
timePlayed += playedFor;
}
document.getElementById("played").innerHTML = Math.round(timePlayed) + "";
// Count as complete only if end of video was reached
if (timePlayed >= duration && event.type == "ended") {
document.getElementById("status").className = "complete";
}
}
function getDuration() {
duration = video.duration;
document.getElementById("duration").appendChild(new Text(Math.round(duration) + ""));
console.log("Duration: ", duration);
}
video.addEventListener("play", videoStartedPlaying);
video.addEventListener("playing", videoStartedPlaying);
video.addEventListener("ended", videoStoppedPlaying);
video.addEventListener("pause", videoStoppedPlaying);
var data = "This user has finished the video";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
//sends hearder info along with the request
http.setRequestHeader("content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(data);
and Data.php has
<?php
$data = $_POST['data'];
$file = fopen('names.txt', 'a');
fwrite($file, $data);
fclose($file);
?>
As of now, there are no errors in the console, but it does not write the data to the text file.
Please let me know what i'm doing wrong
Since you are using http.setRequestHeader("content-type", "application/x-www-form-urlencoded");, the request expects the data to be formatted like serialized HTML form data. Change the following line to provide the data in the proper format:
var data = "data=This%20user%20has%20finished%20the%20video";
I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile
I am using rtcmulticonnection.js. I want to save the video on server. Here are two files "index.html" and "save.php".
request.open("POST", url); does not post the data
here the source file link
"https://github.com/muaz-khan/RTCMultiConnection/blob/master/v2.2.2/demos/audio-video-screen-sharing-recording.html"
index.html
document.getElementById('recordAudioVideo').onclick = function() {
var localVideoStream = rmc.streams.selectFirst({
video: true,
local: true
});
if (!localVideoStream) return;
var recordingSession = {
audio: true,
video: true
};
var button = this;
if (button.innerHTML == 'Record Audio/Video') {
button.innerHTML = 'Stop Recording Audio/Video';
// http://www.rtcmulticonnection.org/docs/startRecording/
localVideoStream.startRecording(recordingSession);
} else if (button.innerHTML == 'Stop Recording Audio/Video') {
// http://www.rtcmulticonnection.org/docs/stopRecording/
localVideoStream.stopRecording(function(blob) {
//alert('Audio blob size in bytes: ' + blob.audio.size);
//alert('Video blob size in bytes: ' + blob.video.size);
var fileType = 'video'; // or "audio"
var fileName = 'ABCDEF.webm'; // or "wav"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
console.log(formData);
xhr('save.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open("POST", url);
request.send(data);
}
button.innerHTML = 'Record Audio/Video';
}, recordingSession);
}
save.php
<?php
// Muaz Khan - www.MuazKhan.com
// MIT License - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = './'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
the problem is at
request.open("POST", url);
request.send(data);
request.open("POST", url); does not post the data.it does not call url(means save.php).because i have alert some text to see if save.php is called or not. so it does not show any alertbox on client.how can i solve this problem.Also it shows no error on posting.
I am working on an image upload post part of my site and I am struggeling to be able to upload the image with the date. I am sending the date via $_POST and the files for the images in $_FILES.
Here is my code (Javascript):
(function post_image_content() {
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;
li.appendChild(img);
list.appendChild(li);
}
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
var data = '';
date = document.getElementById('image_date').value;
if(date == ''){
alert('Please select a date!');
return 0;
} else {
data = 'date='+date;
}
document.getElementById("response").innerHTML = "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: "submit_image.php",
type: "POST",
data: formdata + ' ' + data,
processData: false,
contentType: false,
success: function (res) {
$('#images').show();
document.getElementById("response").innerHTML = res;
hideImageUpload();
}
});
}
}, false);
}());
function hideImageUpload(){
$('#image_upload_form').hide(250);
//$('#response').hide(250);
$('#image-list').hide(250);
}
And the PHP:
<?php
require_once 'core/init.php';
$user = new User();
$errors = $_FILES["images"]["error"];
$date = $_POST['date'];
$date = explode("/", $date);
$newdate = $date[2] + '-' + $date[0] + '-' + $date[1];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
//$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = explode("_", $name);
$imagename='';
foreach($name as $letter){
$imagename .= $letter;
}
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" . $user->data()->id . '_' . $imagename);
$user->create('photos', array(
'osid' => $user->data()->id,
'user' => $user->data()->username,
'gallery' => 'Uploads',
'filename' => "images/uploads/" . $user->data()->id . '_' . $imagename,
'date' => $newdate
));
}
}
echo "<h2>Successfully Uploaded Images</h2>";
I am new to web development, and I am using PDO to enter into database.
Wait... data: formdata + ' ' + data, It is slightly confusing. You add FormData object and string containing url-encoded data.
Append date value to your formdata object: formdata.append('date', date). After this, send AJAX query with data: formdata, only.
But there may be more errors.
For debugging, use Chrome developer tools. You can use debugger and console.log(something) for breakpoint and printing your vars. Also, you always can use step-by-step debugging.