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();
}
Related
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);
});
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;
});
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.
I am uploading images and want to show separate progress bar for each image.
This kind of similar structure I want to create dynamically in jQuery. Here I m trying to create img element uploaded by input file and want to create html container classname 'preview' and put into already created #images tag by using jQuery. Will you please anyone fix it? so frustrated and thanks in advance to all intelligent brains here.
<div id="images"> // already exist
<div class="preview" id="rand">
<img src="background/balance.jpg" id="rand"/>
<div class="progressbar" id="rand">
</div> // this is the preview container to create and put by dynamically in jQuery function
</div>
this is my jQuery function.
function handleFile(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileReader=new FileReader();
var rand = Math.floor((Math.random()*100000)+3); /* this is created for assign id attribute to div and img tag to differentiate each other */
var imageElem=document.createElement("img");
imageElem.id=rand;
var div = document.createElement('div');
div.className = 'preview';
div.id = rand;
var progress = document.createElement('div');
progress.className='progressbar';
progress.id=rand;
fileReader.onload = (function(img)
{
return function(e)
{
img.src = e.target.result;
};
}) (imageElem);
/* here I am trying to create that structure */
document.getElementById("images").appendChild(imageElem); /* and need to append here */
fileReader.readAsDataURL(file);
// document.getElementById("areatext").style.display = "none";
document.getElementById("submit1").style.display = "block";
document.getElementById("submit2").style.display = "block";
uploadFile(file,rand);
}
}
function uploadFile(file,rand) {
var xhr = new Array();
xhr[rand] = new XMLHttpRequest();
var formData = new FormData();
formData.append('myFile[]',file);
xhr[rand].upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
$(".progressbar[id='"+rand+"']").css("width",(e.loaded / e.total) * 100 + "%");
}
}, false);
xhr[rand].open("POST", "drop.php");
xhr[rand].overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr[rand].send(formData);
}
I am using jquery + the hashchange plugin from ben alman. Below is a standard way to grab the hash name and load in content
$(window).hashchange(function() {
var hash = location.hash;
var array_url = hash.split('#');
var page = $(array_url).last()[0];
$('#content').load( page + '.php', function(){
});
});
But is there any way to do this by grabbing some other variable assigned on a click function or sorted through php, perhaps?
I am working with a multi-artist portfolio site that hands out unique three-four letter codes to images
I'd like to serve these images up through unique urls. This has to be through ajax for many reasons.
I had difficulty adding other ajax history options because this page is already using ajax pagination (to load this content) and lots of htaccess url modrewrites.
I am thinking this might just be impossible.
Here is my current code
$('a.photo').click(function () {
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
return false;
});
$(window).hashchange( function(){
var hash = location.hash;
var url = ( hash.replace( /^#/, '' ) || 'blank' );
document.title = url;
})
$(window).hashchange();
and my html / php :
$thethumb = customuniqueidfunc();
<a href="[IMG URL]"
class="photo gotdesc nohover" rel="<?php echo $row['description'] ?>"
id="<?php echo $thethumb; ?>">
This works insofar as the image from the href attr loads into the #content div and the hash from the id attr is added as a hash to the url and to the title of the page, but I am lacking any mechanism to combine the click and the hashchange function, so that each hash actually corresponds to the image.
One method I've used for this before is to run a hash polling function. You can see it in action at this page:
http://www.webskethio.com/#services
Here is the javascript for that page:
http://www.webskethio.com/ws.js
Relevant code:
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
$(document).ready(function(){
/* code removed for readability */
setInterval('pollHash()',100); // Important piece
/* code removed for readability */
});
and
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
}
[EDIT :] Here is the full code for your page that should work, provided you can create a page that just outputs the image's location from the database.
var recentHash = "";
var image_url ="";
$(document).ready(function() {
$('a.photo').click(function (event) {
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
event.preventDefault();
});
setInterval('pollHash()',100);
});
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
if(pageId != ""){
var temp_url = 'http://whitecu.be/user/mountain/'+pageId+'.html';
$.get(temp_url, function(data) {
image_url = data;
image = new Image();
image.src = image_url;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
});
}else{
window.location = "http://whitecu.be/user/mountain";
}
}