1. 程式人生 > >spring MVC檔案上傳和實時進度提醒

spring MVC檔案上傳和實時進度提醒

@RequestMapping(value = "/getProgress.do", method = RequestMethod.POST, produces = { "application/json" })
    @ResponseBody
    public Double getProgress(HttpServletRequest request, HttpServletResponse response) {
        if (request.getSession().getAttribute("upload_ps") == null) {
            return
0.00; } ProgressEntity ps = (ProgressEntity) request.getSession().getAttribute("upload_ps"); Double percent = 0d; if (ps.getpContentLength() != 0L) { percent = (double) ps.getpBytesRead() / (double) ps.getpContentLength() * 1.0d; // 百分比 if (percent != 0
d) { DecimalFormat df = new DecimalFormat("0.00"); percent = Double.parseDouble(df.format(percent)); } } return percent; } @RequestMapping(value = "/upLoadFiledir.do", method = RequestMethod.POST, produces = { "application/json" }) @ResponseBody
public void upLoadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] file) { System.out.println("開始"); // 檔案儲存路徑 String path = request.getSession().getServletContext().getRealPath("upload"); for (int i = 0; i < file.length; i++) { String fileName = file[i].getOriginalFilename(); File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } try { file[i].transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } } }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script type="text/javascript">
    function progress(){
        $.post('<%=request.getContextPath()%>/publicdoc/getProgress.do',{},function(data){
            $("#progress").attr("data-percent",data*100+"%");
            $("#progress-bar").width(data*100+"%");
        });
    }
    var InterValObj;
    function doUpload() {
        layer.open({
            type: 1,
            content:  $('#progress'),
            area: ['400px', '200px'],
            title:'上傳檔案',
            end:function(){//層銷燬回撥函式
                $("#progress").attr("data-percent","0%");
                $("#progress-bar").width("0%");
            },
            closeBtn: 2
        });
        var formData = new FormData($("#form")[0]);
        InterValObj = window.setInterval(progress, 500); //啟動計時器,1秒執行一次
         $.ajax({  
              url: '<%=request.getContextPath()%>/publicdoc/upLoadFiledir.do' ,  
              type: 'POST',  
              data: formData,
              async: true,  
              cache: true,  
              contentType: false,
              processData: false,  
              success: function (returndata) {
                layer.msg("上傳成功",{icon:6});
                $("#progress").attr("data-percent","100%");
                $("#progress-bar").width("100%");
                window.clearInterval(InterValObj);//停止計時器
              },  
              error: function (returndata) {  
              }
        });
    }  
</script>
    <form id="form" enctype="multipart/form-data">  
    選擇檔案:<input type="file" name="file" multiple="multiple" id="file">
        <input type="button" value="提交" onclick="doUpload()">
    </form>

    <div class="progress" data-percent="0%" id="progress" style="width: 300px;display: none;margin: auto;margin-top: 50px">
        <div class="progress-bar" style="width:0%;" id="progress-bar"></div>
    </div>
</body>
</html>