提问人:Meghan M 提问时间:11/9/2023 最后编辑:Karl KnechtelMeghan M 更新时间:11/9/2023 访问量:86
上传图片未显示
Uploading Image is not showing up
问:
我尝试了这个 HTML 来制作一个允许上传图像的表单:
<!-- Title -->
<h2 id="cyor-h2">Create your own Recipe</h2>
<img id="food-image" class="square-recipe-img" style="display:none;" src="no-image.jpg">
<button id="cyor-button" onclick="createButton()">Begin</button>
<!-- Select Image -->
<button><label for="image_input">Update Image</label></button>
<input style="display:none;" type="file" accept="image/png, image/jpeg, image/jpg, image/webp" id="image_input">
<script>
let foodImage = document.getElementById("food-image");
let inputFile = document.getElementById("image_input");
inputFile.onchange= myFunction()
function myFunction() {
foodImage.src = URL.createObjectURL(inputFile.file[0]);
}
</script>
当我尝试使用它时,图像没有显示出来。为什么不呢?
答:
0赞
Utsav
11/9/2023
#1
我希望这对你的事业有所帮助,对于使用js的简单文件上传功能,你可以在js中使用API,它非常简单。您创建的输入字段正是我们将要使用的字段,唯一的区别是我们将引入一个事件,该事件将该标签中的图像 src 更改为读者刚刚解释的标签。FileReader
change
img
我不确定你要用这个按钮做什么,所以我在我的代码中删除了它。
查看实现的代码片段。 Begin
const imageInput = document.getElementById("image_input");
const selectedImage = document.getElementById("selected_image");
imageInput.addEventListener("change", function() {
const file = imageInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
selectedImage.src = e.target.result;
selectedImage.style.display = "block";
};
reader.readAsDataURL(file);
} else {
selectedImage.style.display = "none";
}
});
<h2>Upload The Recipe</h2>
<input type="file" accept="image/png, image/jpeg, image/jpg, image/webp" id="image_input">
<br>
<img id="selected_image" style="max-width: 300px; max-height: 300px; display: none;">
0赞
ASr
11/9/2023
#2
有三个问题:
inputFile.onchange = myFunction()
使用括号将使函数在脚本运行时立即被调用,但在调用事件时不会被调用。相反,使用此选项将允许在事件发生时调用该函数。inputFile.onchange = myFunction
解决第一个问题后,您需要使用属性 not 。您需要进行此修改files
file
foodImage.src = URL.createObjectURL(inputFile.file[0])
确保将属性更改为类似 from .您可以通过在函数中添加以下内容来执行此操作,如下所示:style = display:none
block
none
foodImage.style.display = "block";
不过,使用 instead 会是一个更好的选择,因为在我看来,它使您的代码看起来更干净,但这只是我的个人意见。addEventListener
onchange
评论
inputFile.onchange= myFunction()
inputFile.onchange
myFunction()
()