Skip to content

Instantly share code, notes, and snippets.

@raazon
Last active August 5, 2019 09:37
Show Gist options
  • Save raazon/d11bfc09d3a8a6da06528bcf3e16b4a9 to your computer and use it in GitHub Desktop.
Save raazon/d11bfc09d3a8a6da06528bcf3e16b4a9 to your computer and use it in GitHub Desktop.
HTML input type=file, get the image before submitting the form jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>How to upload preview image before upload through JavaScript</title>
</head>
<body>
<!-- Source URL: https://stackoverflow.com/questions/5802580/html-input-type-file-get-the-image-before-submitting-the-form -->
<input type="file" onchange="readURL(this);" />
<img id="preview" src="http://placehold.it/62x62" alt="Image Alt" />
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview')
.attr('src', e.target.result)
.width(62)
.height(62);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment