Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
<!DOCTYPE html>
<html lang="ja">
<meta charset="UTF-8">
<title>FileAPI で画像を選択またはドラッグ&ドロップし、表示</title>
html, body {
font-size: 20px;
text-align: center;
div#drop-zone {
margin: 1rem auto;
width: 20rem;
height: 10rem;
border: 1px solid #333;
div#print_image {
margin: 1rem auto;
textarea {
width: 100%;
height: 10rem;
margin: 1rem auto;
<h1>FileAPI で画像を選択またはドラッグ&ドロップし、表示</h1>
<input type="file" id="file-image" accept="image/*">
<div id="drop-zone">ここにドロップ!</div>
<div id="print_img">
<p id="width-height">width: height: </p>
<img id="image" alt="">
<textarea name="name" id="print_DataURL" readonly></textarea>
(function() {
var print_img_id = 'print_img';
var print_DataURL_id = 'print_DataURL';
if (checkFileApi()){
var file_image = document.getElementById('file-image');
file_image.addEventListener('change', selectReadfile, false);
var dropZone = document.getElementById('drop-zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleDragDropFile, false);
// FileAPIに対応しているか
function checkFileApi() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
return true;
alert('The File APIs are not fully supported in this browser.');
return false;
function selectReadfile(e) {
var file =;
var reader = new FileReader();
reader.onload = function(){
readImage(reader, print_img_id, print_DataURL_id);
function handleDragOver(e) {
e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
function handleDragDropFile(e) {
var files = e.dataTransfer.files; // FileList object.
var file = files[0];
var reader = new FileReader();
reader.onload = function(){
readImage(reader, print_img_id, print_DataURL_id);
function readImage(reader, print_image_id, print_DataURL_id ){
var result_DataURL = reader.result;
var img = document.getElementById('image');
var src = document.createAttribute('src');
src.value = result_DataURL;
document.getElementById(print_DataURL_id).value = result_DataURL;
printWidthHeight('image', 'width-height');
//width, height表示
function printWidthHeight( img_id, width_height_id ) {
var img = document.getElementById(img_id);
var w = img.naturalWidth;
var h = img.naturalHeight;
document.getElementById(width_height_id).innerHTML = 'width:' + w + ' height:' + h;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.