[.html]
<div id="divImg">
<input id="Img" name="Img" type="file">
<img id="img" style="display:none;" src="" alt="圖片">
</div>
[.js]
var files;
$("#Img").change(function () {
if (this.files && this.files[0]) {
FilePrepareUpload(this.files[0], this.files);
}
});
$('#divImg').on('drop', function (e) {
if (e.originalEvent.dataTransfer) {
if (e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
FilePrepareUpload(e.originalEvent.dataTransfer.files[0], e.originalEvent.dataTransfer.files);
}
}
});
function updateProgress(evt) {
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
if (percentLoaded < 100) {
$(".Progress").css("width", percentLoaded + '%');
}
}
}
function FilePrepareUpload(originalFiles, dataFile) {
var uploadErrors = [];
var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i;
if (originalFiles['type'].length && !acceptFileTypes.test(originalFiles['type'])) {
uploadErrors.push("檔案格式錯誤,請上傳 .gif/.jpg/.jpeg/.png!");
}
if (originalFiles['size'] > 4096000) {
uploadErrors.push("檔案太大!");
}
if (uploadErrors.length > 0) {
//upload file error massege.
alert(uploadErrors.join("\n"));
} else {
if (dataFile && dataFile[0]) {
//process bar set 0%
var reader = new FileReader();
reader.onprogress = updateProgress;
reader.onload = function (e) {
$("#img").attr("src", e.target.result);
$("#img").css("display", "");
//process bar set 100%
}
reader.readAsDataURL(dataFile[0]);
//close process bar.
files = dataFile;
}
}
}
留言
張貼留言