The previous article has implemented the overall HTML and CSS of this project:
This blog is directly based on the previous one. The final effect is:
Rendering 1:
Okay, please allow me to post the picture twice so that everyone can see the effect~
You can see it The html of the li that produces our pictures is actually quite complicated, so I made some modifications to the html document:
<span style="font-size:12px;"><body> <p id="uploadBox"> </p> <p id="template" class="hidden"> <li> <img src=""/> <span class="progress"></span> <span class="percentage"></span> </li> </p> </body></span>
Js code:
<span style="font-size:12px;">/**
* User: zhy
* Date: 14-6-16
* Time: 下午11:06
*/
var ZhangHongyang = {};
ZhangHongyang.html5upload = (function ()
{
var _ID_UPLOAD_BOX = "uploadBox";
var _CLASS_PROGRESS = "progress";
var _CLASS_PERCENTAGE = "percentage";
var _tip_no_drag = "将文件拖拽至此区域,即可上传!";
var _tip_drag_over = "释放鼠标立即上传!";
var _uploadEle = null;
/**
* 初始化对象与事件
* @private
*/
function _init()
{
_uploadEle = document.getElementById(_ID_UPLOAD_BOX);
_uploadEle.ondragenter = _onDragEnter;
_uploadEle.ondragover = _onDragOver;
_uploadEle.ondragleave = _onDragLeave;
_uploadEle.ondrop = _onDrop;
_setStatusNoDrag();
};
/**
* 正在拖拽状态
* @private
*/
function _setDragOverStatus()
{
if (_checkContatinsElements())return;
_uploadEle.innerText = _tip_drag_over;
_uploadEle.style.border = "2px dashed #777";
$(_uploadEle).css({lineHeight: $(_uploadEle).height() + "px"});
}
/**
* 初始化状态
* @private
*/
function _setStatusNoDrag()
{
if (_checkContatinsElements())return;
_uploadEle.innerText = _tip_no_drag;
_uploadEle.style.border = "2px dashed #777";
$(_uploadEle).css({lineHeight: $(_uploadEle).height() + "px"});
}
/**
* 上传文件
* @private
*/
function _setDropStatus()
{
if (_checkContatinsElements())return;
_uploadEle.innerText = "";
_uploadEle.style.border = "1px solid #444";
$(_uploadEle).css({lineHeight: "1em"});
$(_uploadEle).append("<ul></ul>");
};
/**
* 判断是否已经上传文件了
* @private
*/
function _checkContatinsElements()
{
return !!$(_uploadEle).find("li").size();
}
/**
* 当ondragenter触发
* @private
*/
function _onDragEnter(ev)
{
_setDragOverStatus();
}
/**
* 当ondargmove触发
* @private
*/
function _onDragOver(ev)
{
//ondragover中必须组织事件的默认行为,默认地,无法将数据/元素放置到其他元素中。
ev.preventDefault();
}
/**
* 当dragleave触发
* @private
*/
function _onDragLeave(ev)
{
_setStatusNoDrag();
}
/**
* ondrop触发
* @private
*/
function _onDrop(ev)
{
//drop 事件的默认行为是以链接形式打开,所以也需要阻止其默认行为。
ev.preventDefault();
_setDropStatus();
//拿到拖入的文件
var files = ev.dataTransfer.files;
var len = files.length;
for (var i = 0; i < len; i++)
{
//页面上显示需要上传的文件
_showUploadFile(files[i]);
}
}
/**
* 页面上显示需要上传的文件
* @private
*/
function _showUploadFile(file)
{
var reader = new FileReader();
// console.log(file)
// console.log(reader);
//判断文件类型
if (file.type.match(/image*/))
{
reader.onload = function (e)
{
var formData = new FormData();
var li = $("#template li").clone();
var img = li.find("img");
var progress = li.find(".progress");
var percentage = li.find(".percentage");
percentage.text("0%");
img.attr("src", e.target.result);
$("ul", $(_uploadEle)).append(li);
$(_uploadEle).find("li").size() == 10 && $(_uploadEle).width(($(_uploadEle).width() + 8) + "px").css("overflow", "auto");
formData.append("uploadFile", file);
//上传文件到服务器
_uploadToServer(formData, li, progress, percentage);
};
reader.readAsDataURL(file);
}
else
{
console.log("此" + file.name + "不是图片文件!");
}
}
/**
* 上传文件到服务器
* @private
*/
function _uploadToServer(formData, li, progress, percentage)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/strurts2fileupload/uploadAction", true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest', 'Content-Type', 'multipart/form-data;');
//HTML5新增的API,存储了上传过程中的信息
xhr.upload.onprogress = function (e)
{
var percent = 0;
if (e.lengthComputable)
{
//更新页面显示效果
percent = 100 * e.loaded / e.total;
progress.height(percent );
percentage.text(percent + "%");
percent >= 100 && li.addClass("done");
}
};
xhr.send(formData);
}
//把init方法公布出去
return{
init: _init }
})();
</span>
The comments are very detailed. This time I didn’t use literals to create objects directly because I didn’t I hope that users can access all methods and variables. I use simple closures. It can be seen that almost all methods and variables start with _ because I think they are private and I have not published them. The only ones that are published are It is the init method for users to call. The overall method also uses namespaces, so that the js written by other partners basically does not cause the same problems as variables.
HTML FileApi is used in the above js. Here is an introduction:
1. File object That is what we used above:
: Thu Dec 26 2013 18:45:08 GMT+0800 (China Standard Time)
: "yt_key.png"
##size45524
type"image/png"
webkitRelativePath""##__proto__
FileYou can see that some of the above attributes are included. That is to say, if you use a browser that supports HTML5 and set the onchange event for input=type, the user After selecting a picture or file, you can make a judgment about the display of the picture or the size and type of the file.
2、FileReader主要用于异步读取文件内容,注意是异步的,上例我们使用了它的readAsDataURL的方法,关于DataUri的知识可以自己去百度下。
另外还提供了:readAsText用于读取文本;readAsArrayBuffer和readAsBinaryString方法;
还提供了一些事件:onloadstart, onload, onprogress ,onerror , onloaded , onabort 有兴趣的可以去一个一个查看。
最后页面调用,大功告成:
<span style="font-size:12px;"> <script type="text/javascript" src="jquery-1.8.3.js"></script> <script type="text/javascript" src="js/html5upload.js"></script> <script type="text/javascript"> window.onload = function () { ZhangHongyang.html5upload.init(); } ; </script></span>
The above is the detailed content of HTML5/CSS3 classic case - drag and drop to upload images without plug-in (2). For more information, please follow other related articles on the PHP Chinese website!