Loading an image to a img from input file
In browsers supporting the File API, you can use the FileReader constructor to read files once they have been selected by the user.
Example
document.getElementById('picField').onchange = function (evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
// FileReader support
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
document.getElementById(outImage).src = fr.result;
}
fr.readAsDataURL(files[0]);
}
// Not supported
else {
// fallback -- perhaps submit the input to an iframe and temporarily store
// them on the server until the user's session ends.
}
}
Browser support
- IE 10
- Safari 6.0.2
- Chrome 7
- Firefox 3.6
- Opera 12.02
Where the File API is unsupported, you cannot (in most security conscious browsers) get the full path of a file from a file input box, nor can you access the data. The only viable solution would be to submit the form to a hidden iframe and have the file pre-uploaded to the server. Then, when that request completes you could set the src of the image to the location of the uploaded file.
Preview an image before it is uploaded
imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}
<form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
How to set Image source as Input File using JavaScript?
You can use FileReader
to read the input as a dataURL
and then append that url as the image
src
function read(val) {
const reader = new FileReader();
reader.onload = (event) => {
document.getElementById("divOutput").src = event.target.result;
}
reader.readAsDataURL(val.files[0]);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File uploader</title>
<script src="./script.js" defer></script>
</head>
<body>
<h1>My file uploader</h1>
<input type='file' id='userImage' onchange = "read(this)">
<img id='divOutput'></div>
</body>
</html>
Save and load an image from input
I was incorrect that server side is required. There is a good tutorial on codepen for exactly this codepen found from this blog
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
CSS
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
min-height: 300px;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
img {
max-width: 100%;
}
#fileDisplayArea {
margin-top: 2em;
width: 100%;
overflow-x: auto;
}
Javascript:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
Display selected image from input file
You must use the file reader to validate and allow preview of the uploaded image. the browser disallows the access to local system files for good reason and the file inputs place files in a temporary folder system that the browser is allowed to access.
Here is an example of how to use the File Reader Source
const reader = new FileReader();
reader.onload = function(e) {
// do something with the result
var file = reader.result || e.target.result;
}
reader.readAsDataURL(input.files[0]);
how to show preview of a video and an image selected using the same html input type=file
In order to display any <image>
and <video>
from using the same <input>
button then you must dynamically create such elements as needed.
This means:
- Detect what File type the user selected.
- Create a Path to the selected File.
- Create the relevant Element and set Path as
.src
input. - Remove any pre-existing Element from your container (usually a
<div>
). .append
the newly created Element for display on the page.
No JQuery but this is how you can achieve with regular JavaScript code :
- I used your Div as the container (had to add an
id="display-img-vid-con"
for later reference with JS). - Added a
style=""
withabsolute
position to control the container's X/Y coords using top and left).
( ...experiment with it)
<!DOCTYPE html>
<html>
<body>
<!-- button for selecting image/video -->
<label for="inp-img-vid">
<span> Photos/Videos</span>
<input type="file" accept="image/*, video/*" name="img-vid" id="inp-img-vid">
</label>
<div class="display-img-vid-con" id="img-vid-con" style="top: 30px; left: 250px; position: absolute; z-index: 1" >
<!-- showing selected image here -->
<!-- showing selected video here -->
</div>
</body>
<script>
//$("#inp-img-vid").change( function(){ imgPreview(this); } );
document.getElementById("inp-img-vid").addEventListener("change", onFileSelected, false);
var tmpElement; //will be dynamically changed to Image or Video
var file, file_ext, file_path, file_type, file_name;
function show_Info_popUP()
{
alert("File is selected... " + "\n name : " + file_name + "\n type : " + file_type + "\n ext : " + file_ext );
}
function onFileSelected ( input )
{
//if(input.files && input.files[0])
if( input.target.files[0] )
{
file = input.target.files[0]; // FileList object
file_ext; //# will extract file extension
file_type = file.type; file_name = file.name;
file_path = (window.URL || window.webkitURL).createObjectURL(file);
//# get file extension (eg: "jpg" or "jpeg" or "webp" etc)
file_ext = file_name.toLowerCase();
file_ext = file_ext.substr( (file_ext.lastIndexOf(".")+1), (file_ext.length - file_ext.lastIndexOf(".")) );
//# get file type (eg: "image" or "video")
file_type = file_type.toLowerCase();
file_type = file_type.substr( 0, file_type.indexOf("/") );
let reader = new FileReader();
reader.readAsDataURL(file);
//reader.onload = function(e)
reader.onloadend = function(evt)
{
//# POP-UP ...if you want to show (Alert box with) file details...
show_Info_popUP();
if (evt.target.readyState == FileReader.DONE)
{
//# get container...
let container = document.getElementById("img-vid-con");
//# remove any already existing child element(s)
while (container.firstChild)
{ container.removeChild(container.firstChild); }
//# if IMAGE...
if ( file_type == "image" )
{
tmpElement = document.createElement( "img");
tmpElement.setAttribute("id", "preview-img");
}
//# if VIDEO...
if ( file_type == "video" )
{
tmpElement = document.createElement( "video");
tmpElement.setAttribute("id", "preview-vid");
tmpElement.setAttribute("controls", "true" );
tmpElement.addEventListener("loadeddata", () =>
{
//# what to do when some video data is loaded
if (tmpElement.readyState >= 3)
{
//# what to do when video's first frame is ready
tmpElement.muted = true; //# if you want silent preview
tmpElement.play();
}
});
}
//# finalise display size
tmpElement.width = 640; tmpElement.height = 400;
tmpElement.setAttribute("src", file_path);
container.appendChild(tmpElement);
}
}
}
}
</script>
</html>
Load image into img via input event
For img
tag we need an image path (relative/absolute), not the file name.
Else we can read the file with browser FileReader
API and display the image in data uri
format.
can you check the exmaple below
import React, { useState } from "react";
export default function App() {
const [image, setImage] = useState("");
const handleChange = (file) => {
const input = file.currentTarget;
var reader = new FileReader();
reader.onload = function () {
const dataURL = reader.result;
setImage({ name: input.files[0].name, src: dataURL });
};
reader.readAsDataURL(input.files[0]);
};
return (
<div className="App">
<input
id="inputFile1"
type="file"
accept="image/*"
onChange={handleChange}
/>
<img id="imagen1" src={image.src} alt="your" />
</div>
);
}
Getting image from input file and then add it as a background to a div
You can use something like this.
https://www.w3docs.com/learn-javascript/file-and-filereader.html
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
const fileInput = document.getElementById('imageInput');
const images = document.querySelectorAll('.mole');
fileInput.addEventListener('change', (e) =>{
const file = e.target.files[0];
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (){
images[0].setAttribute('src', fileReader.result);
// images[0].setAttribute('style', `background-image: url('${fileReader.result}')`);
}
})
body {
min-height: 100vh;
margin: 0;
background-color: bisque;
display: grid;
place-content: center;
}
.box{
display: flex;
flex-direction: column;
place-content: center;
align-items: center;
}
input{
margin-bottom: 1rem;
}
.images{
display: flex;
flex-direction: row;
}
.mole {
width: 10rem;
height: 10rem;
margin-bottom: 1rem;
}
<div class="box">
<input type="file" id="imageInput" />
<div class="images">
<img class="mole" />
<img class="mole" />
</div>
</div>
How to allow input type=file to accept only image files?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Related Topics
Request Header Field Access-Control-Allow-Headers Is Not Allowed by Access-Control-Allow-Headers
JavaScript Localstorage Object Broken in Ie11 on Windows 7
How to Change a <Select> Value from JavaScript
Html5 Audio Tag on Safari Has a Delay
Document.Getelementsbyclassname().Innerhtml Always Returns "Undefined"
How to Determine If a Checkbox Is Checked
Enter Key Press Behaves Like a Tab in JavaScript
Formdata.Append("Key", "Value") Is Not Working
How to Use JSON File in HTML Code
HTML Anchor Link - Href and Onclick Both
Access Event to Call Preventdefault from Custom Function Originating from Onclick Attribute of Tag
Reactjs: "Uncaught Syntaxerror: Unexpected Token <"
How to Determine Which HTML Page Element Has Focus
How to Draw a Line Between Two Divs