Skip to content

Instantly share code, notes, and snippets.

@zaru
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save zaru/5efbb00c663dad498f19 to your computer and use it in GitHub Desktop.

Select an option

Save zaru/5efbb00c663dad498f19 to your computer and use it in GitHub Desktop.
file upload
<!--
iOSは動くが(iOS8.0ではバグで動かない)、AndroidBrowserだと動かない…
-->
<!doctype html>
<html>
<head>
<meta charset="utf8">
<style type="text/css">
#upload {
width:90px;
height:35px;
text-align:center;
line-height:35px;
border-radius:5px;
color:#fff;
background-color:#4385bf;
margin:10px 0;
cursor:pointer;
}
#results {
border:1px solid #4385bf;
background-color:#bbd4ea;
height:160px;
padding:5px;
margin:10px 0;
}
#results img {
border:1px solid #000;
margin:0 5px 0 0;
}
</style>
<body>
<input type="file" accept="image/jpeg, image/gif, image/png" id="a" name="files[]" style="">
<form action="index.php" method="post" enctype="multipart/form-data" id="form">
<button type="submit">submit</button>
</form>
<div id="upload">picture</div>
<div id="results"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function() {
var makeInput = function() {
return $('<input type="file" accept="image/jpeg, image/gif, image/png" name="files[]" style="opacity:0;">');
};
$('#upload').click(function() {
var hookInput = makeInput();
var id = 'i' + parseInt((new Date)/1000);
hookInput.attr('id', id);
$('#form').append(hookInput);
$('#' + id).click();
$(hookInput).on('change', setImage);
});
function setImage() {
for (var i = 0; i < this.files.length; i++) {
var id = $(this).attr('id');
var file = this.files[i];
fr = new FileReader();
fr.onload = function(e) {
var img = $('<img>');
img.attr('src', e.target.result);
img.css('height', '160px');
$('#results').append(img);
$(img).on('click', {id: id}, removeImage);
};
fr.readAsDataURL(file);
}
}
function removeImage(e) {
$(this).remove();
$('#' + e.data.id).remove();
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment