PHP Record sound and upload php with progressbar - php

I used the code at the link for recording audio and upload to server.
I found some upload progressbar codes but could not merge with this code.
Audio records may be 30-40 mb and upload takes long time.
How can I add upload status for this code below?
https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/
var upload = document.createElement('a');
upload.href="#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, filename);
fd.append("filename",blob, 'audiofile');
xhr.open("POST","upload.php",true);
xhr.send(fd);
alert('Uploaded');
}) ```

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(event)
{
var progress = event.loaded / event.total * 100;
console.log('Progress: ' + progress);
});

Related

Download button under all images WordPress

I have a WordPress site with a huge number of images and I want to add the ability to download each one. they are contained in posts (one post contains 50-100 images). I tried using the "Files Download Delay" with the search by file extension feature, but the button doesn't appear.
Are there any template scripts? or how can the idea be realized?
Thank you
jQuery(".wp-block-image").each(function() {
var imageurl = jQuery(this).find("img").attr("src");
var download_html =`<div class="download-link">
<a href="javascript:void(0);"
id="download_nopurchased" class="click_download icon-download" data-
href="${imageurl}" download="${imageurl}" data-url="${imageurl}"><i
class="fas fa-download"></i> Download Now </a>
</div>`;
jQuery(this).append(download_html);
});
jQuery(".click_download").click(function() {
var file = jQuery(this).data("url");
var file_name = getFileName(file);
forceDownload(file,file_name);
});
function getFileName(str) {
return str.substring(str.lastIndexOf('/') + 1)
}
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}

jquery ajax file upload with progressbar uploading same file multiple times

i am creating media-bank where user can upload media files and can reuse later
image,audio and videos can be uploaded with the following options
image upload from pc, specify link
audio upload from pc, specify link
video upload from pc, youtube url, facebook embed code
separate forms are created in tabbed layout with class="FormUpload"
upload from pc forms has <input type="file" name="file".../>
while all other forms has <textarea name="file" ...>
my database table looks like
[id, file, type, src,...]
[1, pic.png, image, pc,...]
[2, http://domin/img.png, image, link,...]
$('body').on('submit','.FormUpload',function(e){
e.preventDefault();
var pr = $(this).parents('.tabPanes').find('.progressBar');
var lbl = $(this).parents('.tabPanes').find('.percentLabel');
var url = $(this).attr('action');
var data = new FormData();
if($(this).find('#txtFile[type="file"]').length === 1 ){
data.append('file', $(this).find( '#txtFile' )[0].files[0]);
}else{
data.append('file', $(this).find('#txtFile' ).val());
}
data.append('type',$(this).find('#txtType').val());
data.append('src',$(this).find('#txtSrc').val());
data.append('title',$(this).find('#txtTitle').val());
data.append('tags',$(this).find('#txtTags').val());
if($(this).find('#txtFile[type="file"]').length === 1){//if file is being uploaded from pc
pr.val(100);
fileForm(url,data,pr,lbl);
}else{//else link is provided
linkForm(url,data,pr,lbl);
pr.val(0);
}
return false;
});
function fileForm(url,data,pr,lbl){
`enter code here`$.ajax({
url : url,
type: "POST",
data : data,
contentType: false,
cache: false,
processData:false,
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
pr.val(percent);
}, false);
}
return xhr;
},
mimeType:"multipart/form-data",
}).done(function(res){ //
frm[0].reset();
lbl.html(res);
});
linkForm() also looks like fileForm()
the issue is when I upload image from PC it uploads the same image 3-times some time 5-times in folder as well as database.
I debuged and noticed network tab, ajax request to php file is also being sent multiple times.
tried to replace all jquery code by the following but still same issue but this time frequency looks reduced
$('body').on('submit','.FormUpload',function(e){
e.preventDefault(); //prevent form normal submition
//get progressbar label url_to_hit and form_reference into variables to be used below
var pr = $(this).parents('.tabPanes').find('.progressBar');
var lbl = $(this).parents('.tabPanes').find('.percentLabel');
var url = $(this).attr('action');
var frm = $(this);
//populate formdata
var data = new FormData();
if(frm.find('#txtFile[type="file"]').length === 1 ){
data.append('file', frm.find( '#txtFile' )[0].files[0]);
}else{
data.append('file', frm.find('#txtFile' ).val());
}
data.append('type',frm.find('#txtType').val());
data.append('src',frm.find('#txtSrc').val());
data.append('title',frm.find('#txtTitle').val());
data.append('tags',frm.find('#txtTags').val());
//prepare ajax and callback functions
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener('progress',function(evt){
var percentage = (evt.loaded/evt.total)*100;
pr.val(Math.round(percentage));
lbl.html(Math.round(percentage)+'% uploaded.');
},false);
ajax.addEventListener('load',function(evt){
lbl.html(evt.target.responseText);
pr.val(0);
},false);
ajax.addEventListener('error',function(evt){
lbl.html('upload failed');
pr.val(0);
},false);
ajax.addEventListener('abort',function(evt){
lbl.html('upload aborted');
pr.val(0);
},false);
ajax.open('POST',url);
ajax.send(data);
//again stop form submition (optional)
return false;
});

Saving a base 64 image creates a blank image in PHP

First here's my client side code:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
img.onload = function(){
canvas.width = 600;
canvas.height = 400;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
}
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
})
And here's my php code:
$imageArr = explode(',', $_POST['image']);
$image = base64_decode($imageArr[1]);
file_put_contents('image.jpg',$image);
I'm resizing the image on the client side and then sending it as a data url to php to then be saved as an image.
When I save an image it creates a blank image on my server. BUT when I save another image without refreshing the page it saves the previous image in it's place and this time correctly. This is beyond me, can someone please shed some light?
You are sending the image before it is loaded. Your img.onload function is executed after xhttp.send(data). When you upload one more time it gets previous image which is already loaded.
Try following:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 400;
var ctx = canvas.getContext('2d');
img.onload = function(){
ctx.drawImage(img,0,0,canvas.width,canvas.height);
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
}
})
A possibility to keep in mind: Since everything on client side is setup in the file input's onChange event handler, maybe some setup code is launched in the wrong order and/or not in time to be used as intended? Then, when invoking the onChange event again, resources are already in place /has already been initialized and the image gets displayed as intended.
It's just a theory. To investigate, try to move initializations out of the event handler scope.

How to bind a jquery dialog with html element after refreshing the data using ajax response?

In my php page I got a jquery script to open a dialog window. The code is as
<script type="text/javascript">
$(document).ready(function() {
var $loading = $('<img src="loading.gif" alt="loading" class="loading">');
$('#data-specs a').each(function() {
var $dialog = $('<div></div>')
.append($loading.clone());
var $link = $(this).one('click', function() {
$dialog
.load($link.attr('href'))
.dialog({
title: '<?php echo $_GET["indQ"];?>',
modal: true,
width: 500,
height: 300,
minHeight: 300,
maxHeight: 600,
minWidth: 500,
maxWidth: 800
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
return false;
});
});
$('#dav').val(getURLParameter('davQ'));
$('#pathogen').val(getURLParameter('pathogenQ'));
$('#topicF').val(getURLParameter('topicQ'));
$('#ind').val(getURLParameter('indQ'));
$('#subind').val(getURLParameter('subindQ'));
$(".selfont").change(function (event) {
window.location = '?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val() + '&indQ=' + encodeURIComponent($('#ind').val()) + '&subindQ=' + encodeURIComponent($('#subind').val());
});
function getURLParameter(name) {
return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
});
</script>
The data is in a table with id='data-specs'. And it works well. Recently I added a dropdown box with values to sort this table using an ajax script and it works too. But the problem is after this ajax call, when I click the link to open dialog window its getting opened in the parent window itself, if we press the browser back button and then click the link it will open the dialog window with no errors !! How can I make this correct even after the sort is done using ajax ? please gave me some solutions. My ajax code to sort is as shown below
function ajaxFunction(){
//to keep selection in countryList - GP
var ref = document.getElementById('countryRF');
for(i=0; i<ref.options.length; i++)
ref.options[i].selected = true;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//document.myForm.time.value = ajaxRequest.responseText;
document.getElementById("result").innerHTML=ajaxRequest.responseText
}
}
var dav = document.getElementById('dav').value;
var pathogen = document.getElementById('pathogen').value;
var topicF = document.getElementById('topicF').value;
var ind = document.getElementById('ind').value;
var subind = document.getElementById('subind').value;
var selObj = document.getElementById('countryRF');
var cnty = loopSelected(selObj).join('~'); // join array into a string
var sortby = document.getElementById('sortby').value;
var queryString = "?dav=" + dav + "&pathogen=" + pathogen + "&topicF=" + topicF + "&ind=" + encodeURIComponent(ind) + "&subind=" + encodeURIComponent(subind) + "&cnty=" + encodeURIComponent(cnty) + "&sortby=" + sortby;
ajaxRequest.open("GET", "sortbyD.php" + queryString, true);
ajaxRequest.send(null);
return false;
}
Please help me to slve this issue..
While the page is load first time the dialog box event are bound with element, After ajax you need to again bound the dialog box event with .bind() function

Uploading files using XMLHttpRequest

I'm trying to use a drag and drop plugin in javascript to upload files using ajax.
<script>
DnD.on('#drop-area', {
'drop': function (files, el) {
el.firstChild.nodeValue = 'Drag some files here.';
var names = [];
[].forEach.call(files, function (file, i) {
names.push(file.name + ' (' + file.size + ' bytes)');
var xhr = new XMLHttpRequest();
xhr.open('POST','upload.php');
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(file);
console.log(xhr.responseText);
});
document.querySelector('#dropped-files p i').firstChild.nodeValue = names.join(', ');
}
});
</script>
And here's upload.php:
<?php
print_r($_POST);
?>
Basically I haven't written the script to upload the file yet because I'm still figuring out how can I have access to the data that I've sent through JavaScript. Can you guide me on what to do next? How do I access the file from upload.php.
Try to use FormData instead of xhr:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
You have access to your file with this array:
<?php var_dump($_FILES["thefile"]); ?>
See more: http://www.w3schools.com/php/php_file_upload.asp

Categories