This time I will show you how to use jquery to upload and load files. What are the precautions for using jquery to upload and load files? The following is a practical case, let's take a look.
Uploading files is achieved by dragging files. The ondrop event of HTML5 is mainly used. Upload content channel FormData transmission:
//进度条 <p class="parent-dlg" > <p class="progress-label">0%</p> <p class="son"></p> </p> //要拖动到的地方 <p class="main_content_center"></p>
js:
var dz = $('#main_content_center'); dz.ondragover = function(ev) { //阻止浏览器默认打开文件的操作 ev.preventDefault(); } dz.ondrop = function(ev) { ev.preventDefault(); var files = ev.dataTransfer.files; var len = files.length,i = 0; while (i < len) { var filesName=files[i].name; var extStart=filesName.lastIndexOf("."); var ext=filesName.substring(extStart,filesName.length).toUpperCase(); if(ext!=".JPG"&&ext!=".PNG"&&ext!=".XML"){ //判断是否是需要的问件类型 TS.errorAlert("请选择.jpg、.png、.xml类型的文件上传!"); return false; }else{ test(files[i]); } i++; } $(".parent-dlg").show(); } function test(a){ var formData = new FormData(); formData.append("name", a.name); formData.append("size", a.size); formData.append("data", a); $.ajax({ url:'', type:'post', data:formData, cache: false, processData: false, contentType: false, xhr: function(){ var xhr = $.ajaxSettings.xhr(); if(onprogress && xhr.upload) { xhr.upload.addEventListener("progress" , onprogress, false); return xhr; } } }) }; function onprogress(evt){ var loaded = evt.loaded; //已经上传大小情况 var tot = evt.total; //附件总大小 var per = Math.floor(100*loaded/tot); //已经上传的百分比 $(".progress-label").html( per +"%" ); $(".son").css("width" , per +"%"); if(per>=100){ $(".parent-dlg").hide(); } }
Progress Article css:
.parent-dlg{position: absolute;width:400px; height:20px; border:1px solid #aaaaaa;border-radius:3px;top:30%;left:50%;z-index:9999;margin-left:-200px;display:none;} .parent-dlg .progress-label{position: absolute;left: 50%;top: 4px;font-weight: bold;text-shadow: 1px 1px 0 #fff;} .parent-dlg .son {width:0; height:100%; background-color:#cccccc; text-align:center; line-height:20px; font-size:16px; font-weight:bold;}
This content is just a general technical direction for file uploading, which can be improved according to your own project!
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
webpack.config.js parameter usage tutorial
How to use p5.js keyboard in the project Interaction
The above is the detailed content of How to use jquery to upload files. For more information, please follow other related articles on the PHP Chinese website!