删除文件时不显示任何内容



function previewImage() {
var thisElement = event.target
var file = thisElement.files;
var fileReader = new FileReader();
fileReader.onload = function(event) {
thisElement.nextElementSibling.querySelector("img").setAttribute("src", event.target.result);
}
if (file.length) {
fileReader.readAsDataURL(file[0])
} else {
fileReader.readAsDataURL()
}
};
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="row">
<div class="border border-dark d-flex align-items-center justify-content-center bg-warning">
<h4 class="d-inline">PHOTO*</h4>
</div>
</div>
<div class="row">
<div class="border border-dark">
<input type="file" id="file1" accept="image/*" class="form-control" onchange="previewImage();" required>
<label for="file1" class="d-flex align-items-center justify-content-center" style="height: 170px;">
<img id="display1" class="w-100 h-100" style="cursor: pointer;">
</label><br>
</div>
</div>

我使一个表单,我需要上传图片,显示它&它显示。但问题是,当我删除图像时它也会显示图像。

if-else语句中不需要fileReader.readAsDataURL();。仅if语句是预览图像所必需的。

使用readAsDataURL()方法读取指定Blob或File的内容。参数在该方法中是必需的。这是你的else语句中缺少的。

function previewImage() {
let thisElement = event.target;
let file = thisElement.files;
let fileReader = new FileReader();
let img = document.querySelector("img"); 
fileReader.onload = function(event) {
img.setAttribute("src", event.target.result);
};
if (file.length) {
fileReader.readAsDataURL(file[0]);
} else {
img.src='';
}
};
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="row">
<div class="border border-dark d-flex align-items-center justify-content-center bg-warning">
<h4 class="d-inline">PHOTO*</h4>
</div>
</div>
<div class="row">
<div class="border border-dark">
<input type="file" id="file1" onchange="previewImage()" accept="image/*" class="form-control" required>
<label for="file1" class="d-flex align-items-center justify-content-center" style="height: 170px;">
<img id="display1" class="w-100 h-100" style="cursor: pointer;">
</label><br>
</div>
</div>

相关内容

  • 没有找到相关文章

最新更新