Home >Web Front-end >JS Tutorial >How to implement file drag and drop upload
When I first started, I found an example on the Internet. This example mentioned that drag-related events need to be blocked on the document. The default processing method for all events, the code is as follows:
$(document).on({ dragleave:function(e){ //拖离 e.preventDefault(); }, drop:function(e){ //拖后放 e.preventDefault(); }, dragenter:function(e){ //拖进 e.preventDefault(); }, dragover:function(e){ //拖来拖去 e.preventDefault(); } });
In fact, in our file upload, the area that accepts drag and drop is generally only a small area, so I simplified it as follows
$drop.on("dragenter", function (e) { e.preventDefault(); console.log("enter"); $drop.addClass("hover");});$drop.on("dragleave drop", function (e) { e.preventDefault(); console.log("leave"); $drop.removeClass("hover");});$drop.on("dragover", function (e) { e.preventDefault();})
Moreover, during the enter event, a hover style is added to the target area to highlight the accepting area
The default is Jiang purple (So this style should be removed in the drop and leave events)
because they need to be processed at the same time input box and drag area, so my html structure is as follows:
<p class="row" id="dropBox" @drop.prevent="Change($event)"> <p class="import-data"> <button :class="{'disabled' : resultMsg.length > 0}" class="btn btn-info"> <i class="fa fa-cloud-upload text"></i> 选择文件 </button> <span :class="{'error-tips':isError}">{{msg}}</span> <input type="file" v-show="resultMsg.length == 0" @change="Change($event)" name="importExcel" class="importExcel" value="" /> </p> <br> <p class="loading" :style="'width:'+loading+'%'"></p> </p>
is the drop event of #dropBox
and input
The change event is also bound to the Change
function and the event object is passed into the function
Here, I added the prevent
modifier to the drop
event. Shield the default event. If the event is not blocked, the accepting area #dropBox
will not be able to receive the file, and the file will trigger the browser to download (if it cannot be previewed directly) or preview;
Change:function(ev){ var e = window.event || ev; var file = e.target.files ? e.target.files[0] : e.dataTransfer.files[0]; if(!file){ vm.msg = "点击选择,或者拖拽填写好数据的excel文件致此"; vm.isError = true; return false } },
ps: The business logic in the js code is hidden and only the public part is described.
When accepting files selected by the user, use e.target.files
As a judgment condition, to determine whether there is a file selected by input, if so, take e.target.files[0]
, if not, take e.dataTransfer.files[0]
.
The properties of these two event objects are hung on the event object by the browser according to different situations.
The above is the detailed content of How to implement file drag and drop upload. For more information, please follow other related articles on the PHP Chinese website!