您的位置:首页 > 编程语言 > Java开发

springMVC+ajax 文件上传 带进度条

2016-05-16 18:20 483 查看
前端代码
<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>        <br />    <br />    <br />    <br />    <progress id="progressBar" value="0" max="100"></progress>    <span id="percentage"></span>    <br />    <br />    <br />    <br /><form id= "uploadForm">    <input type="file" id="file" name="myfile" />    <input type="button" onclick="UpladFile()" value="上传" /></form>
后端代码
@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";    }

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: