I have this JS function using which I'm using to upload files from HTML multi-file uploader to dropbox using Javascript SDK. It's working well. Now I'm trying to add list of file names that are failed to upload(when catch block executes) to a string named "failed", but it's adding the name of the first file for all the failed files. What am I doing wrong here?
function uploadFile() {
var count1=0,count2=0,loop=0, failed='';
const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024;
var ACCESS_TOKEN = 'SomeAccessToken';
var dbx = new Dropbox.Dropbox({
accessToken: ACCESS_TOKEN
});
var fileInput = document.getElementById('file-upload');
var formp= document.getElementById('formp');
for (var i = 0; i < fileInput.files.length; i ) {
formp.innerHTML='<p> Uploading ' fileInput.files.length ' files </p>' ;
var file = fileInput.files[i];
var filename = fileInput.files[i].name;
if (file.size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
dbx.filesUpload({path: '/Test/' file.name, contents: file})
.then(function(response) {
var results = document.getElementById('results');
var br = document.createElement("br");
results.appendChild(document.createTextNode(file.name 'File uploaded!'));
results.appendChild(br);
count1=count1 1;
if(count1 count2==fileInput.files.length)
{
formp.innerHTML='<p> Uploaded ' count1 ' files. Failed ' count2 ' files</p>';
}
console.log(response);
})
.catch(function(error) {
count2=count2 1;
console.error(error);
failed =file.name;
if(count1 count2==fileInput.files.length)
{
formp.innerHTML='<p> Uploaded ' count1 ' files. Failed ' count2 ' files</p>';
}
});
}
}
CodePudding user response:
//sticky
const newDiv = document.createElement("div");
newDiv.classList.add("sticky-div");
document.querySelector("body").appendChild(newDiv);
// pick product name
var productName = document.querySelector(".product-single__title").innerText;
var productPrice = document.querySelector(".product__price").innerText;
newDiv.innerHTML =
""
'<span >'
productName
"</span>"
'<div >'
' <span >'
productPrice
"</span>"
' <button .btn--full").getAttribute("class")
'" disabled>'
document.querySelector(".btn--full").innerHTML
"</button>"
"</div>";
const sizeOptions = document.querySelectorAll(
'fieldset[name="Size"] .variant-input'
);
for (let i = 0; i < sizeOptions.length; i ) {
sizeOptions[i].addEventListener("click", function () {
// console.log('size clicked');
// console.log(document.querySelector('.btn--full').innerHTML);
document.querySelector(".stickyCTA").innerText = "Add to Bag";
document.querySelector(".stickyCTA").disabled = false;
});
}
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".sticky-div {"
" background: #e4e4e4;"
" padding: 10px 20px;"
" "
" display: flex;"
" justify-content: space-between;"
" "
" position: fixed;"
" top: 60px;"
" width: 100%;"
"}"
""
".text-bold {"
" font-weight: bold;"
"}"
""
".innerFlex {"
" display: flex;"
" align-items: center;"
"}";
document.getElementsByTagName("head")[0].appendChild(style);
//edit
const submitButton = document.querySelector(".btn--full");
document.addEventListener("scroll", () => {
console.log("123");
checkScrolled(submitButton);
});
const checkScrolled = (element) => {
const bottomPix = element.getBoundingClientRect().bottom;
if (bottomPix <= 50) {
newDiv.style.display = "flex";
} else {
newDiv.style.display = "none";
}
};
const stickyButton = document.querySelector(".stickyCTA");
stickyButton.onclick = function () {
submitButton.click();
};
const tabDiv = document.createElement("div");
tabDiv.classList.add("tab-container");
document.querySelector(".np-global-content").appendChild(tabDiv);
// const tabLink = document.createElement('div');
// tabLink.classList.add('tab');
// tabDiv.appendChild(tabLink);
function showDetails(evt, type) {
console.log(type);
var i, tabcontent, tablinks;
// Get all elements with and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i ) {
tabcontent[i].style.display = "none";
}
// Get all elements with and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i ) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(type).style.display = "block";
evt.currentTarget.className = " active";
}
const locationContent = document.querySelector("#np-echotex-content").innerHTML;
const materialContent = document.querySelector("#np-organic-content").innerHTML;
// materialContent.classList.add('tabcontent');
tabDiv.innerHTML =
""
'<div >'
'<button onclick="showDetails(event,`location`)">'
"Location"
"</button>"
'<button onclick="showDetails(event, `material`)">'
"Material"
"</button>"
"</div>"
'<div id="location">'
locationContent
"</div>"
'<div id="material">'
materialContent
"</div>";
//slideMine
function waitForElement() {
if(document.querySelectorAll('.product-recommendations .aos-animate .grid__item .grid-product__content .grid-product__link .grid-product__image-mask .image-wrap .lazyautosizes.lazyloaded')[3]) {
console.log("helooooooo");
const refNode = document.querySelector('#shopify-section-product-recommendations');
var sliderHTML = ''
'<div >'
'<div >'
'</div>'
'<a onclick="plusSlides(-1)">❮</a>'
'<a onclick="plusSlides(1)">❯</a>'
'<div >'
'</div>'
'<div >'
' <div >'
' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_720x.jpg?v=1650973749" style="width:100%" onclick="currentSlide(1)" alt="The Woods">'
'</div>'
'<div >'
' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_720x.jpg?v=1650973749" style="width:100%" onclick="currentSlide(2)" alt="Cinque Terre">'
'</div>'
'<div >'
' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_720x.jpg?v=1650973749" style="width:100%" onclick="currentSlide(3)" alt="Mountains and fjords">'
'</div>'
'<div >'
' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_720x.jpg?v=1650973749" style="width:100%" onclick="currentSlide(4)" alt="Northern Lights">'
'</div>'
'</div>'
'</div>';
refNode.insertAdjacentHTML("afterend", sliderHTML);
// var imageArr = document.querySelectorAll('.product-recommendations .aos-animate .grid__item .grid-product__content .grid-product__link .grid-product__image-mask .image-wrap .lazyautosizes.lazyloaded');
var imageArr = document.querySelectorAll('.product-recommendations .aos-animate .grid__item')
console.log("imaghes",imageArr);
imageArr.forEach(function(value,index){
const image = value.querySelector('.grid-product__content .grid-product__link .grid-product__image-mask .image-wrap .lazyautosizes.lazyloaded');
const caption =
console.log(image.getAttribute('srcset'),index);
var slideDiv = document.querySelector('.slide-div');
//var sliderRef = document.querySelector('.slideshow-container');
var captionCont = document.querySelector('.caption-container');
var eachItem = '<div >'
' <div >' (index 1) '/ 6</div>'
' <img src="' image.getAttribute('srcset') '" style="width:100%">'
'<p>' image.getAttribute('alt') '</p>'
'</div>';
slideDiv.insertAdjacentHTML("beforeend",eachItem); showSlides(slideIndex);
// var eachCaption = '<p id="caption">' image.getAttribute('alt') ' </p>';
// captionCont.insertAdjacentHTML("beforeend",eachCaption);
});
}
else {
setTimeout(waitForElement, 25);
}
}
waitForElement();
let slideIndex = 1;
//showSlides(slideIndex);
function plusSlides(n) {
console.log("clicked",n);
showSlides(slideIndex = n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
console.log(slides);
//let dots = document.getElementsByClassName("demo");
//let captionText = document.getElementById("caption");
//let captionContainer = document.querySelector('.caption-container');
//let captions = document.querySelectorAll('.caption-container #caption');
//console.log("captions",captions[slideIndex-1]?.innerHTML);
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i ) {
slides[i].style.display = "none";
}
//for (i = 0; i < dots.length; i ) {
// dots[i].className = dots[i].className.replace(" active", "");
//}
slides[slideIndex-1].style.display = "block";
//captionContainer.innerHTML =captions[slideIndex-1]?.innerHTML;
//dots[slideIndex-1].className = " active";
//captionText.innerHTML = captions[slideIndex-1].alt;
//captions.innerHTML = '<span>' captions[slideIndex-1]?.innerHTML '</span>';
};
//css mine
#Recommendations-7592407171330{
/*display: none;*/
}
* {
box-sizing: border-box;
}
/* Position the image container (needed to position the left and right arrows) */
.slideshow-container {
position: relative;
}
/* Hide the images by default */
.mySlides {
display: none;
}
/* Add a pointer when hovering over the thumbnail images */
.cursor {
cursor: pointer;
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 40%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* Container for image text */
.caption-container {
text-align: center;
background-color: #222;
padding: 2px 16px;
color: white;
}
#caption{
display: none;
}
.row:after {
content: "";
display: table;
clear: both;
}
/* Six columns side by side */
.column {
float: left;
width: 25%;
}
/* Add a transparency effect for thumnbail images */
.demo {
opacity: 0.6;
}
.active,
.demo:hover {
opacity: 1;
}
//SlideShad
function waitForElement() {
if(document.querySelector('footer').length) {
} else {
setTimeout(waitForElement, 25);
}
}
waitForElement();
var refNode = document.querySelector('.np-desktop-only .product__photos');
var sliderHTML = ''
'<div >'
''
'<div >'
'</div>'
// ' <div >'
// ' <div >1 / 3</div>'
// ' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_1800x1800.jpg?v=1650973749" style="width:100%">'
// ' <div >Caption Text</div>'
// ' </div>'
''
// ' <div >'
// ' <div >2 / 3</div>'
// ' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_1800x1800.jpg?v=1650973749" style="width:100%">'
// ' <div >Caption Two</div>'
// ' </div>'
// ''
// ' <div >'
// ' <div >3 / 3</div>'
// ' <img src="https://cdn.shopify.com/s/files/1/0283/1338/7053/products/NCTW-0618-n-p-Oatmeal_lookbook_2_1800x1800.jpg?v=1650973749" style="width:100%">'
// ' <div >Caption Three</div>'
// ' </div>'
''
' <a onclick="plusSlides(-1)">❮</a>'
' <a onclick="plusSlides(1)">❯</a>'
' <div >'
'</div>'
'</div>'
'<br>'
'';
// ' <div >'
// '<div >'
// '<img src="img_woods.jpg" style="width:100%" onclick="currentSlide(1)" alt="The Woods">'
// ' </div>'
// ' <div >'
// '<img src="img_5terre.jpg" style="width:100%" onclick="currentSlide(2)" alt="Cinque Terre">'
// '</div>'
// '<div >'
// '<img src="img_mountains.jpg" style="width:100%" onclick="currentSlide(3)" alt="Mountains and fjords">'
// '</div>'
// '<div >'
// '<img src="img_lights.jpg" style="width:100%" onclick="currentSlide(4)" alt="Northern Lights">'
// '</div>'
// '<div >'
// '<img src="img_nature.jpg" style="width:100%" onclick="currentSlide(5)" alt="Nature and sunrise">'
// '</div>'
// '<div >'
// '<img src="img_snow.jpg" style="width:100%" onclick="currentSlide(6)" alt="Snowy Mountains">'
// '</div>'
refNode.insertAdjacentHTML("afterend", sliderHTML);
var currentImageArr = document.querySelectorAll('.np-desktop-only .product__photos .np-main-slide .photoswipe__image');
currentImageArr.forEach(function(value, index) {
console.log(value.getAttribute('data-src'), index);
var sliderRefNode = document.querySelector('.slideshow-container');
var slideDiv = document.querySelector('.slide-div');
var eachItem = ' <div >'
' <div >' (index 1) ' / ' currentImageArr.length '</div>'
' <img src="' value.getAttribute('data-photoswipe-src') '" style="width:100%">'
' <div >Caption Text</div>'
' </div>';
var eachThumbnail =
'<div >'
'<img src="' value.getAttribute('data-photoswipe-src') '" style="width:100%" onclick="currentSlide(' (index 1) ')" alt="The Woods">'
' </div>';
const row = document.querySelector('.row');
showSlides(slideIndex);
slideDiv.insertAdjacentHTML('beforeend', eachItem);
row.insertAdjacentHTML('beforeend',eachThumbnail);
});
let slideIndex = 1;
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex = n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i ) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i ) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className = " active";
}
//css sahd
.np-desktop-only .product__photos {
display: none;
}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Hide the images by default */
.mySlides {
display: none;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .demo:hover {
background-color: #717171;
}
/* Fading animation */
.fade {
animation-name: fade;
animation-duration: 1.5s;
}
.row:after {
content: "";
display: table;
clear: both;
}
/* Six columns side by side */
.column {
float: left;
width: 11%;
}
.cursor {
cursor: pointer;
}
.demo {
opacity: 0.6;
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
CodePudding user response:
As far as I have seen, I dint find anything wrong in this code. For testing purpose I commented few lines of your code and tested. The files names are properly concatenated to the "failed" string.
<form>
<input type="file" id="formp" multiple="true" accept="*/*" />
</form>
<pre></pre>
$('#formp').change(function (event) {
var count1=0,count2=0,loop=0, failed='';
const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024;
var ACCESS_TOKEN = 'SomeAccessToken';
/* var dbx = new Dropbox.Dropbox({
accessToken: ACCESS_TOKEN
}); */
var fileInput = document.getElementById('formp');
var formp= document.getElementById('formp');
for (var i = 0; i < fileInput.files.length; i ) {
formp.innerHTML='<p> Uploading ' fileInput.files.length ' files </p>' ;
var file = fileInput.files[i];
var filename = fileInput.files[i].name;
failed =file.name;
console.log('Failed check', failed);
if (file.size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
// dbx.filesUpload({path: '/Test/' file.name, contents: file})
// .then(function(response) {
// var results = document.getElementById('results');
// var br = document.createElement("br");
// results.appendChild(document.createTextNode(file.name 'File uploaded!'));
// results.appendChild(br);
// count1=count1 1;
// if(count1 count2==fileInput.files.length)
// {
// formp.innerHTML='<p> Uploaded ' count1 ' files. Failed ' count2 ' files</p>';
// }
// console.log(response);
// })
// .catch(function(error) {
// count2=count2 1;
// console.error(error);
// failed =file.name;
// if(count1 count2==fileInput.files.length)
// {
// formp.innerHTML='<p> Uploaded ' count1 ' files. Failed ' count2 ' files</p>';
// }
// });
}
}
});
Try the above code in jsFiddle.
There might be a chance that the first file name might be cached in file variable and might be displaying the same variable name for each and every loop again and again. So emptying the "file" variable at the end of the each loop might fix the issue.