Created
July 4, 2013 10:31
-
-
Save Leko/5926643 to your computer and use it in GitHub Desktop.
ブラウザにファイルをドロップし、情報と内容を表示するhtmlとjs
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
(function(global, $) { | |
"use strict"; | |
var util = { | |
// ブラウザのデフォルトの動作と、イベントの伝播をキャンセルする | |
stop: function(e) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
}, | |
// strを指定の長さで切り取る | |
cutoff: function(str, len, tail) { | |
tail = tail || ""; | |
return str.slice(0, len) + tail; | |
} | |
} | |
$(function() { | |
var $dropArea = $("#dropable"); | |
// ドラッグ関連のイベントをすべてキャンセルして、ドロップイベントを設定 | |
$dropArea.on({ | |
"dragenter": util.stop, | |
"dragover": util.stop, | |
"dragleave": util.stop, | |
"drop": function(e) { | |
util.stop(e); | |
// filesはargumentsのようなオブジェクトなので配列に変換 | |
var tmp = e.originalEvent.dataTransfer.files, | |
files = Array.prototype.slice.call(tmp, 0, tmp.length); | |
files.forEach(function(file) { | |
var reader = new FileReader(); | |
// 読み込みが完了した時のイベントを設定 | |
$(reader).one('load', function(e) { | |
var fn = "ドロップされたファイル名:" + file.name, | |
ft = "ファイルの形式:" + file.type, | |
fs = "ファイルサイズ:" + file.size + " Byte", | |
fv = "内容:" + util.cutoff(e.target.result, 80, "...[略]"), | |
msg = [fn, ft, fs, fv].join("\n"); | |
$dropArea.append( $("<pre></pre>").text(msg) ); | |
}); | |
// ファイルをテキストとして読み込む | |
reader.readAsText(file); | |
}); | |
} | |
}); | |
}); | |
}(this, jQuery)); |
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 lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>ファイルドロップをキャンセルするサンプル</title> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> | |
<script src="filedrop.js"></script> | |
</head> | |
<body> | |
<div id="dropable">ここにファイルをドロップしてみて下さい</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment