Image preview

I’m trying to do this…,


It doesn’t appear to work, but no error in the console…
Heres the HML


<div id="add_site" class="overlay">
	<div class="popup" style="width:25%;margin-top:25px">
		<div class="content">
			<div class="card">
			  <a class="close" href="#">&times;</a>
			  <h3 class="card-header"><span class="icon-plus"></span>&nbsp;&nbsp;Add A Site</h3>
				<div class="card-body">
					<div class="alert alert-light border border-light shadow-sm" role="alert">
					  <form action="sites/add_site_engine.php" method="POST" enctype="multipart/form-data">
						 <div class="mb-3">
							<label for="site_Name">Name</label>
							<input type="text" class="form-control" id="site_Name" name="Name" required>							 
						</div>
						<div class="mb-3">			 
						  <label for="customFile1" class="form-label">Floorplan (image)</label>
						  <input class="form-control" type="file" id="customFile1" name="Floorplan" accept="image/png">
						</div>
						<div class="mb-3">			 
							<div class="Image_Container" id="Image_Preview_Container">
							  <img src="" alt="Image Preview" class="Image_Preview">
							  <span class="Image_Preview_Default_Text">Image Preview</span>
							</div>
						</div>	
						<div class="mb-3">
							<div class="d-grid">
							  <button class="btn btn-outline-dark btn-lg" type="submit"><span class="icon-ok"></span>&nbsp;&nbsp;Submit</button>
							</div>
						</div>				
					  <input type="hidden" value="1" name="location_id">
					  </form>	
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
			  

<script>
const inpfile = document.getElementById("customFile1");
const previewContainer = document.getElementById("Image_Preview_Container");
const previewImage = previewContainer.querySelector(".Image_Preview");
const previewImageText = previewContainer.querySelector(".Image_Preview_Default_Text");

inpfile.addEventListener("change", function() {
previewImage.setAttribute("src", this.result);
const file = this.files[0];
	
	if(file) {
		const reader = new FileReader();
		
		previewImageText.style.display = "none";
		previewImage.style.display = "block";
		
		reader.addEventListener("load", function() {
			previewImage.setAttribute("src", this.result);
	});	
			
	reader.readAsDataURL(file);
	
	} else {
		previewImageText.style.display = null;
		previewImage.style.display = null;
		previewImage.setAttribute("src", '');
		
	}
});
</script>

I think everything is referenced correctly, so what is the problem?

“I’m trying to do this”

What is “this”?

when I select an image, a preview of it should appear in the dotted box, so i know what im uploading

I am not sure but I don’t think you can give image raw data as an src attribute of a html image.

I guess you need to base64 encode it and setup it as inline image like described here

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.