如何使用输入文件API-vanilla Javascript在CSS后台URL属性中显示上传的图像



初始项目有一个数组,其中存储了文件名,图像滑块会显示这些文件名。

我正在尝试创建上传功能,用户可以上传图像,然后将该图像推送到阵列中。

我曾尝试在上传的文件上使用URL.createObjectURL方法,并将其推到显示器上,但当幻灯片到达数组索引时出现错误。

文件显示为"blob:http等等…",所以我尝试从字符串中删除"blob",但仍然收到错误。

HTML:

<div id="container">
<button class="button" id="leftButton"><i class="fa fa-arrow-left"></i></button>
<button class="button" id="rightButton"><i class="fa fa-arrow-right"></i></button>
</div>
<div class="upload">
<p><input type='file' name='image' id="input"></p>
</div>

CSS:

#container {
margin: 100px auto;
height: 500px;
width: 900px;
border: 7px solid #3e92cc;
border-radius: 10px;
background: url('images/one.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}

Javascript:

let container = document.getElementById("container");
let rightButton = document.getElementById("rightButton");
let leftButton = document.getElementById("leftButton");
let images = ["one.jpg", "two.jpg", "three.jpg", "four.jpg", "five.jpg"];
let imagesIndex = 0;
const inputElement = document.getElementById("input");
let newURL;
//Add background to slider
function addBackground() {
if (!images[imagesIndex].includes('http')) {
container.style.background = `url('images/${images[imagesIndex]}')`;
} else {
container.style.background = `url('${images[imageIndex]}')`;
}
container.style.backgroundPosition = "center";
container.style.backgroundRepeat = "no-repeat";
container.style.backgroundSize = "cover";
}
// upload files 
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
const objectURL = window.URL.createObjectURL(fileList[0]);
//remove 'blob:';
newURL = objectURL.replace('blob:', '');
console.log(newURL);
images.push(newURL);
}
// Event listeners
inputElement.addEventListener("change", handleFiles, false);
rightButton.addEventListener("click", function () {
imagesIndex++;
if (imagesIndex >= images.length) {
imagesIndex = 0;
}
console.log(imagesIndex);
addBackground();
})
leftButton.addEventListener("click", function () {
imagesIndex--;
if (imagesIndex < 0) {
imagesIndex = images.length - 1;
}
console.log(imagesIndex);
addBackground();
})

不要删除blob:这在URL方案中是必需的

// upload files 
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
const objectURL = window.URL.createObjectURL(fileList[0]);
//remove 'blob:';
//newURL = objectURL.replace('blob:', '');
console.log(objectURL);
images.push(objectURL);
}

更正imagesIndex中的打字错误

//Add background to slider
function addBackground() {
if (!images[imagesIndex].includes('http')) {
container.style.background = `url('images/${images[imagesIndex]}')`;
} else {
container.style.background = `url('${images[imagesIndex]}')`;
}
//.. other code
}