springMVC+ajax实现文件上传且带进度条实例
前端代码:
<formid="uploadForm"> <p>指定文件名:<inputtype="text"name="filename"value=""/></p> <p>上传文件:<inputtype="file"name="file"/></p> <inputtype="button"value="上传"onclick="doUpload()"/> </form> functiondoUpload(){ varformData=newFormData($("#uploadForm")[0]); $.ajax({ url:'http://localhost:8080/xiaochangwei/file/upload', type:'POST', data:formData, async:false, cache:false, contentType:false, processData:false, success:function(returndata){ alert(returndata); }, error:function(returndata){ alert(returndata); } }); }
后端:
@RequestMapping(value="/upload",method=RequestMethod.POST) publicStringupload(HttpServletRequestrequest,@RequestParam("file")MultipartFilefile,ModelMapmodel){ System.out.println("开始"); Stringpath=request.getSession().getServletContext().getRealPath("upload"); StringfileName=file.getOriginalFilename(); //StringfileName=newDate().getTime()+".jpg"; System.out.println(path); FiletargetFile=newFile(path,fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try{ file.transferTo(targetFile); }catch(Exceptione){ e.printStackTrace(); } model.addAttribute("fileUrl",request.getContextPath()+"/upload/"+fileName); return"result"; }
如果前端有很多实体类数据同文件一同提交
可以修改后端方法为:
upload(HttpServletRequestrequest,@RequestParam("file")MultipartFilefile,ModelMapmodel,Useruser)
利用下面的代码更可实现带有进度条的文件上传
<scripttype="text/javascript"> functionUpladFile(){ varfileObj=document.getElementById("file").files[0];//js获取文件对象 varFileController="http://localhost:8080/xiaochangwei/file/upload";//接收上传文件的后台地址 //FormData对象 varform=newFormData($("#uploadForm")[0]); //XMLHttpRequest对象 varxhr=newXMLHttpRequest(); xhr.open("post",FileController,true); xhr.onload=function(){ //alert("上传完成!"); }; xhr.upload.addEventListener("progress",progressFunction,false); xhr.send(form); } functionprogressFunction(evt){ varprogressBar=document.getElementById("progressBar"); varpercentageDiv=document.getElementById("percentage"); if(evt.lengthComputable){ progressBar.max=evt.total; progressBar.value=evt.loaded; percentageDiv.innerHTML=Math.round(evt.loaded/evt.total*100)+"%"; if(evt.loaded==evt.total){ alert("上传完成100%"); } } } </script> <progressid="progressBar"value="0"max="100"></progress> <formid="uploadForm"> <inputtype="file"id="file"name="myfile"/> <inputtype="button"onclick="UpladFile()"value="上传"/> </form>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。