-
-
Save image72/2c4f8be85539aa12b3aadcd3bf0b88c7 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/naguhi / file upload preview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
<style> | |
#container > img { | |
width: 200px; | |
height: 200px; | |
} | |
</style> | |
<script> | |
function sendFile(option, cb) { | |
/* { | |
field: name, | |
url : '/path/to/upload', | |
file : FileObject | |
} */ | |
var field = option.field, | |
xhr = new XMLHttpRequest(), | |
fd = new FormData(), | |
resp; | |
xhr.open("POST", option.url, true); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState == 4 && xhr.status == 200) { | |
// Handle response. | |
resp = JSON.parse(xhr.responseText); | |
cb && cb(resp); | |
} | |
}; | |
xhr.addEventListener('load', function () { | |
resp = JSON.parse(xhr.responseText); | |
//cb(resp); | |
}, false); | |
// send multiple files; | |
//var files = Array.apply(null,option.file); | |
//files.forEach(function(item) { | |
// fd.append(field, item, item.name); | |
//}) | |
fd.append(field, option.file); | |
// Initiate a multipart/form-data upload | |
xhr.send(fd); | |
} | |
$(function() { | |
function readURL(file) { | |
console.log(typeof file); | |
var reader = new FileReader(); | |
reader.onload = function(e) { | |
$('#container').append('<img src="' + e.target.result+ '">') | |
} | |
reader.readAsDataURL(file); | |
} | |
$('#prefiles').on('change', function(ev) { | |
var $that = $(this), | |
files = Array.apply(null, this.files); | |
$.each(files, function(i, file) { | |
readURL(file); | |
}) | |
}) | |
}) | |
</script> | |
</head> | |
<body> | |
<input type="file" name="prefiles" id="prefiles" multiple> | |
<div id="container"> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment