springMVC+ajax实现文件上传且带进度条实例
更新时间:2017年01月18日 09:40:18 作者:肖哥哥
本篇文章主要介绍了springMVC+ajax实现文件上传且带进度条实例,具有一定的参考价值,有兴趣的可以了解一下。
前端代码:
<form id= "uploadForm"> <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上传文件: <input type="file" name="file"/></ p> <input type="button" value="上传" onclick="doUpload()" /> </form> function doUpload() { var formData = new FormData($( "#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) public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, ModelMap model) { System.out.println("开始"); String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); // String fileName = new Date().getTime()+".jpg"; System.out.println(path); File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName); return "result"; }
如果前端有很多实体类数据同文件一同提交
可以修改后端方法为:
复制代码 代码如下:
upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, ModelMap model,User user)
利用下面的代码更可实现带有进度条的文件上传
<script type="text/javascript"> function UpladFile() { var fileObj = document.getElementById("file").files[0]; // js 获取文件对象 var FileController = "http://localhost:8080/xiaochangwei/file/upload"; // 接收上传文件的后台地址 // FormData 对象 var form = new FormData($( "#uploadForm" )[0]); // XMLHttpRequest 对象 var xhr = new XMLHttpRequest(); xhr.open("post", FileController, true); xhr.onload = function () { // alert("上传完成!"); }; xhr.upload.addEventListener("progress", progressFunction, false); xhr.send(form); } function progressFunction(evt) { var progressBar = document.getElementById("progressBar"); var percentageDiv = 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> <progress id="progressBar" value="0" max="100"></progress> <form id= "uploadForm"> <input type="file" id="file" name="myfile" /> <input type="button" onclick="UpladFile()" value="上传" /> </form>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
mybatis plus saveBatch方法方法执行慢导致接口发送慢解决分析
这篇文章主要为大家介绍了mybatis plus saveBatch方法导致接口发送慢解决分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10idea2019版Plugins中搜索不到任何插件的问题解决
本文主要介绍了idea2019版Plugins中搜索不到任何插件的问题解决,插件搜不出来的主要原因是plugins.jetbrains.com ping不通,下面就来介绍一下解决方法,感兴趣的可以了解一下2023-09-09
最新评论