Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created Jun 21, 2021
Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
label,
input {
display: block;
width: 100%;
}
input {
margin-bottom: 1em;
}
#app {
margin-bottom: 1em;
}
img {
height: auto;
max-width: 100%;
}
</style>
</head>
<body>
<h1>File Upload</h1>
<div id="app"></div>
<form id="upload">
<label for="file">File to upload</label>
<input type="file" id="file" accept="image/*">
<button>Upload</button>
</form>
<script>
// Get the form and file field
let form = document.querySelector('#upload');
let file = document.querySelector('#file');
let app = document.querySelector('#app');
/**
* Log the uploaded file to the console
* @param {event} Event The file loaded event
*/
function logFile (event) {
let str = event.target.result;
let img = document.createElement('img');
img.src = str;
app.append(img);
console.log(str);
}
/**
* Handle submit events
* @param {Event} event The event object
*/
function handleSubmit (event) {
// Stop the form from reloading the page
event.preventDefault();
// If there's no file, do nothing
if (!file.value.length) return;
// Create a new FileReader() object
let reader = new FileReader();
// Setup the callback event to run when the file is read
reader.onload = logFile;
// Read the file
reader.readAsDataURL(file.files[0]);
}
// Listen for submit events
form.addEventListener('submit', handleSubmit);
</script>
</body>
</html>
@mems

This comment has been minimized.

Copy link

@mems mems commented Jul 15, 2021

You can replace base64 URI with Blob URI (shorter code and use less CPU/memory):

function handleSubmit (event) {

	// Stop the form from reloading the page
	event.preventDefault();

	// If there's no file, do nothing
	if (!file.value.length) return;

	// Read the file
	let uri = URL.createObjectURL(file.files[0]);
	let img = document.createElement('img');
	img.src = uri;
	app.append(img);
	console.log(uri);
	
	// Revoke the blob URI (this URI can't be reused)
	URL.revokeObjectURL(uri);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment