How to count no. of image files in local folder using javascript - javascript

I am new to JavaScript and am trying simple web design. I have a doubt that how to get no.of image files stored in local image folder using js code.
I would like to get the no. of image files dynamically so that even if we are adding more images in folder any time that also will be displayed on web page.
function parenting {
var n=3;
for(var i=1; i<=n; i++) {
var img1 = document.createElement('img');
img1.src = 'images/parenting/'+i+'.jpg';
document.body.appendChild(img1);
}
}
In above code, i have given n=3 as default no. of image files but it should be taken from image folder by code.

If you enable directory browsing on your web server for your images location, then you can do an ajax request and iterate over the results:
$.ajax({
url: "images/parenting/",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='images/parenting/" + filename + "'>");
});
}
});
Here's a vanilla JavaScript answer:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var n = (xmlhttp.responseText.match(/jpg/g) || []).length;
for (var i = 1; i <= n; i++) {
var img1 = document.createElement('img');
img1.src = 'images/parenting/' + i + '.jpg';
document.body.appendChild(img1);
}
}
}
};
xmlhttp.open("GET", "images/parenting/", true);
xmlhttp.send();

Related

JSON Parse Javascript Issues

I am using the following to load a local txt file to convert it, the code is directly from W3c schools but the page loads nothing on screen and I have no errors on page or in the inspector. It wont work on MAMP or webserver. I am trying to learn vanilla JS so I don't want to use a library or jquery.
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "array.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Thanks for your help everyone, the issue was a clash with another function running on the page and the lack of 200 response from the local file.

Having trouble dynamically writing HTML in Chrome

Okay, so I am working on code to display all the images in a folder as a gallery. I've got a PHP script to find all the files in the folder (someone else had written it, and it works just fine):
<?php
$directory = $_REQUEST['folder'];
if (!is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
}
echo json_encode($files);
?>
Now I had a javascript get the json from the php and display it in a grid:
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
const gallery = document.getElementById("web_gallery");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
for(var i = 0; i < myObj.length; i++)
{
var write = "<img src='" + folder + "/" + myObj[i] + "' id='gallery_img'>";
console.log(write);
gallery.innerHTML += write;
}
}
};
xmlhttp.open("GET", "toJson.php?folder=" + folder, true);
xmlhttp.send();
This works just fine on Firefox, but it doesn't display anything on Chrome. I looked through several threads here and the one with the most traction seamed to suggest that I should try to use JQuery, so I set that up and wrote this:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var toWrite = [];
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
toWrite.push("<img src='" + folder + "/" + images[i] + "' id='gallery_img'>");
//$( "#web_gallery" ).append( write ); // Had this here before, but tried to move it down to after it's done.
}
}).done(function()
{
for(var i = 0; i < toWrite.length; i++)
{
$("#web_gallery").append(toWrite[i]);
}
});
});
Someone else suggested that you shouldn't do so many append requests so I changed it to:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var write = "";
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
write += "<img src='" + folder + "/" + images[i] + "' id='gallery_img'>\n";
}
}).done(function()
{
setTimeout(function () {
$("#web_gallery").append(write);
}, 1500);
});
});
All of these work fine in Firefox, but not a single one of them work in Chrome, and I'm not sure why. It seems to have to do with the time and speed of writing to the page, I think.
Append the image element with the createElement method.
var image = document.createElement('img');
image.src = imageFilePath;
$(image).appendTo("#web_gallery");

How to convert m3u8 URL to mp4 downloadable file in browser?

I am writing an extension to download videos from a website. That web site has mp4 files and m3u8 files. I have already implemented the part to download direct mp4 files. I stuck at converting the m3u8 file to mp4. I tried lot of js packages but there are a lot of dependencies and failed even after using browserfy.
Current popup.js file
function loadvideoList(callback){
chrome.storage.sync.get(['courseID'], function(result) {
if(result.courseID != 'undefined'){
$.ajax({
type: 'GET',
url: "http://localhost:80/get_videos_list/"+result.courseID,
crossDomain: true,
success: function(response) {
document.getElementById("loading_icon").style.display='none';
document.getElementById("videos_list").style.display='block';
document.getElementById("videos_list").style.padding='10px';
for(var i = 0; i < response.video_list.length; i++){
if(response.video_list[i].type == 'mp4'){
handleDownloadButton(response.video_list[i]);
}else{
// ************ HERE ***************
handleDownloadButton-m3u8Tomp4(response.video_list[i].video_url)
}
}
},
error: function (err) {
alert("unexpected error occured: "+err.code);
console.log(err);
}
});
}else{
document.getElementById("videos_list").style.display='none';
document.getElementById("videos_list").style.padding='0';
}
});
}
function handleDownloadButton(json_vid){
var node = document.createElement("DIV");
// node.style.marginBottom = "5px"
var t = document.createElement('p');
t.textContent = json_vid.file_name;
t.style.width ="240px";
node.appendChild(t);
node.style.padding = "5px";
var downloadBtn = document.createElement("BUTTON");
downloadBtn.style.cssFloat = "right";
downloadBtn.className = "btn btn-primary btn-sm download_btn";
downloadBtn.innerHTML = "Download";
// downloadBtn.value = json_vid.video_url;
node.appendChild(downloadBtn);
downloadBtn.id = json_vid.video_id;
document.getElementById("videos_list").appendChild(node);
var progress_bar = document.createElement("DIV");
progress_bar.className = "progress_container";
node.appendChild(progress_bar);
var moving_bar = document.createElement("DIV");
moving_bar.className = "progress_bar";
progress_bar.appendChild(moving_bar);
moving_bar.id = json_vid.video_id+"bar";
$(function(){
$(`#${json_vid.video_id}`).click(function(){
$(`#${json_vid.video_id}`).attr("disabled", true);
// alert(json_vid.video_url);
var that = this;
var page_url = json_vid.video_url;
var req = new XMLHttpRequest();
req.open("GET", page_url, true);
// req.withCredentials = true;
req.addEventListener("progress", function (evt) {
if(evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
// document.getElementById("download_stat").innerHTML = percentComplete;
// console.log(percentComplete);
document.getElementById(json_vid.video_id+"bar").style.width = `${percentComplete*100}%`;
document.getElementById(json_vid.video_id).textContent = `${(percentComplete*100).toFixed(2)}%`;
}
}, false);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
var filename = $(that).data('filename');
if (typeof window.chrome !== 'undefined') {
// Chrome version
$(`#${json_vid.video_id}`).attr("disabled", false);
$(`#${json_vid.video_id}`).attr("onclick", "").unbind("click");
document.getElementById(json_vid.video_id).textContent = 'Save';
$(function(){
$(`#${json_vid.video_id}`).click(function(){
// alert("download is ready");
var link = document.createElement('a');
// link.text = "download is ready";
// document.getElementById("videos_list").appendChild(link);
link.href = window.URL.createObjectURL(req.response);
link.download = json_vid.file_name;
link.click();
});
});
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
var blob = new Blob([req.response], { type: 'application/force-download' });
window.navigator.msSaveBlob(blob, filename);
} else {
// Firefox version
var file = new File([req.response], filename, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
}
};
req.send();
});
});
}
handleDownloadButton function create the button to download the direct mp4 files. I need to implement a similar function called handleDownloadButton-m3u8Tomp4(see the code sample) that should first convert the http://...file.m3u8 to a mp4 and make it also downloadable. I seek for a script in similar repos like https://github.com/puemos/hls-downloader-chrome-extension, but I was unable to do so. It would be great, If anyone could help me, Thanks in advance!
You can try to use ffmpeg.wasm to convert the .m3u8 file to a .mp4 file. ffmpeg.wasm is a pure WebAssembly / JavaScript port of FFmpeg. They even have an example repository for a Chrome extension. I haven't tested it myself though.
There are other questions here on StackOverflow that deal with how to convert a m3u8 file with FFmpeg, like this one for example.

How to fix net::ERR_CONNECTION_RESET when uploading files from javascript to php?

So I've been struggling with this for the past few hours and couldn't find a working solution anywhere.
I've made a multiple file uploader in my website. For a long time it worked well or at least I thought it does. Recently I tryed uploading 3 images (total size 16MB) and at some point it displays this in console:
Failed to load resource: net::ERR_CONNECTION_RESET
This is my upload source:
$("#submitform").click(function() {
var h = document.getElementById("filelist");
if (h.files.length < 1)
return;
$("#state").css("display", "block");
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
$("#state").css("display", "none");
if (xhr.responseText == "")
alert("Files uploaded sucessfully.");
else
alert("Failed to upload files: \n" + xhr.responseText);
location.reload();
}
};
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(e.loaded / e.total * 100);
$("#precentage").html(pc + "%");
}, false);
xhr.open("POST", "uploadImages.php", true);
var data = new FormData();
var j = 0;
for (i = 0; i < h.files.length; i++) {
if ($('#use' + i).val() == 1) {
data.append("image" + j, h.files[i]);
j++;
}
}
xhr.send(data);
});
and uploadImages.php does some basic algorithms that work whenever I try to upload a single image.
My php.ini looks like this:
file_uploads = On
post_max_size = 500M
upload_max_filesize = 500M
curl.cainfo = "/home/accountname/php/cacert.pem"
I've tryed adding cacert.pem but it doesn't fix anything. I'm using godaddy's linux starter pack to host my website, if that matters.

Allow only images in file upload form element in directory HTML5

HTML Code
<input type="file" accept="image/*" multiple webkitdirectory mozdirectory msdirectory odirectory directory id="fileURL"/>
Javascript Code:
var files,
file,
extension,
sum,
input = document.getElementById("fileURL"),
output = document.getElementById("fileOutput"),
holder = document.getElementById("fileHolder")
sizeShow = document.getElementById("filesSize");
input.addEventListener("change", function (e) {
files = e.target.files;
output.innerHTML = "";
sum = 0;
for (var i = 0, len = files.length; i < len; i++) {
file = files[i];
extension = file.name.split(".").pop();
if(extension=="jpg"||extension=="png"){
var size = Math.floor(file.size/1024 * 100)/100;
sum = size+sum;
output.innerHTML += "<li class='type-" + extension + "'>"+file.webkitRelativePath + file.name + " (" + size + "KB)</li>";
}else{
file.remove();
}
}
if(sum<1024*1024){
sizeShow.innerHTML = Math.floor(sum/1024*100)/100 + " MB";
}else if(sum>1024*1024){
sizeShow.innerHTML = Math.floor(sum/1024*1024*100)/100 + " GB";
}
}, false);
How do i get just the image in the file upload? accept="image/*" doesn't work for directory.
This does work but the statement file.remove() doesn't work at all.
I guess the input:file is read-only.
How do i solve this?
You can set input.files to a FileList (obtained from e.g. drag and drop), but you cannot create/modify a FileList. So you cannot modify the files of an input to e.g. only contain images.
What you can do, though, is uploading manually (through ajax), and only send files that have a type starting with "image/". See http://jsfiddle.net/WM6Sh/1/.
$("form").on("submit", function(e) {
e.preventDefault();
var files = $(this).find("input").prop("files");
var images = $.grep(files, function(file) {
return file.type.indexOf("image/") === 0; // filter out images
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "/", true);
$(xhr).on("readystatechange", function(e) {
if(xhr.readyState === 4) {
console.log("Done");
}
});
var data = new FormData();
$.each(images, function(i) {
data.append(i, this); // append each image file to the data to be sent
});
console.log(
"Sending %d images instead of all %d files...",
images.length,
files.length
);
xhr.send(data);
});

Categories