1. 程式人生 > >springMvc多附件上傳帶進度條

springMvc多附件上傳帶進度條

html頁面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>中期成果提交</title>
  <link rel="stylesheet" href="../../layui/css/layui.css">
   <link rel="stylesheet" href="../css/style.css">
<!-- 最新版本的 Bootstrap 核心 CSS 檔案 -->
<link rel="stylesheet"
    href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
    crossorigin="anonymous">
    
 <style>  
    html,body{background: #fff;}
    .article5 {padding: 10px;min-height:330px;border:1px solid #e6e6e6;}
    .article5 .arR span { line-height: 32px; }
    .article6 { height: 32px; padding-left: 40px; margin-bottom: 15px; }
    .article6 .arR span { float: right;}
    .article9 { width: 620px; margin: 25px auto 0; height: 48px; }
    .article9 span { width: 200px; height: 30px; border-radius: 20px; line-height: 30px; text-align: center; font-size: 13px; cursor: pointer}
      .article9 span.arL { background: #0fa4f8; color: #fff; }
      .article9 span.arR { border: 1px solid #eee; color: #999; }
  </style>
</head>
<body>
     <#include "/head2.ftl"/>
     <div class="home_body">
   <#include "/left.ftl"/>
    <div class="home_right">
     <input type="hidden" name="paid" value="${paId}" class="layui-input">
     <span style="color:#0c87ef">選擇附件</span>&nbsp;&nbsp;<span style="color:#0c87ef" id="add">新增</span>
     <h6>請上傳小於10MB的doc,docx,xls,xlsx,txt,PDF格式附件。</h6>
    <form id="uploadForm">
 
        <!-- 由於使用了ssm框架,後臺接收是用name繫結的,注意name和後臺一致 -->
        <input type="file" id="file" name="file" class="file" onchange="fileChange(this);"/>

    </form>
    <div class="progress" style="width: 40%">
        <div id="progressactive"
            class="progress-bar progress-bar-striped active" role="progressbar"
            aria-valuenow="45" aria-valuemin="0" aria-valuemax="100"
            style="width: 0%"></div>
    </div>
    <span id="sr-only"></span>
   <article class="article9 clearfix" >
                    <span class="fl arL" id="submit" onclick="UpladFile()">提交</span>
    </article>
       </div>
  </div>    
  <#include "/foot.ftl"/>
     
    </div>
</body>
  <script src="../../layui/layui.js"></script>
 <script src="../js/index.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
<script
    src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"
    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
    crossorigin="anonymous"></script>
<script type="text/javascript">
     var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    function fileChange(target,id) {
        var fileSize = 0;
        var filetypes =[".rar",".txt",".zip",".doc",".ppt",".xls",".pdf",".docx",".xlsx"];
        var filepath = target.value;
        var filemaxsize = 1024*10;//2M
        if(filepath){
            var isnext = false;
            var fileend = filepath.substring(filepath.lastIndexOf("."));
            if(filetypes && filetypes.length>0){
                for(var i =0; i<filetypes.length;i++){
                    if(filetypes[i]==fileend){
                        isnext = true;
                        break;
                    }
                }
            }
            if(!isnext){
                alert("不接受此檔案型別!");
                target.value ="";
                return false;
            }
        }else{
            return false;
        }
        if (isIE && !target.files) {
            var filePath = target.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            if(!fileSystem.FileExists(filePath)){
                alert("附件不存在,請重新輸入!");
                return false;
            }
            var file = fileSystem.GetFile (filePath);
            fileSize = file.Size;
        } else {
            fileSize = target.files[0].size;
        }
 
        var size = fileSize / 1024;
        if(size>filemaxsize){
            alert("附件大小不能大於"+filemaxsize/1024+"M!");
            target.value ="";
            return false;
        }
        if(size<=0){
            alert("附件大小不能為0M!");
            target.value ="";
            return false;
        }
    }
    $("#add").click(function(){
    var p='<input type="file" id="file" name="file" class="file" onchange="fileChange(this);"/>';
    $("#uploadForm").append(p);
    })
    function UpladFile() {
    var paid=$(" input[ name='paid' ] ").val();
        var fileObj = document.getElementById("file").files[0]; // js 獲取檔案物件
        var FileController = "upResult.do?type=middle&paid="+paid; // 接收上傳檔案的後臺地址
        // FormData 物件
        var form = new FormData($("#uploadForm")[0]);//建立一個form物件
        // XMLHttpRequest 物件
        var xhr = new XMLHttpRequest();//建立XMLHttpRequest物件
        xhr.open("post", FileController, true);//開啟連線,(訪問型別,地址,是否非同步)
        xhr.onload = function() {//請求完成後執行  裡面可用
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                //alert(xhr.responseText);//後臺返回的資料
                alert("上傳成功");
               window.location.href = "cgtj.do";
            } else {
                alert("Request was unsuccessful: " + xhr.status);//狀態
                //0    UNSENT (未開啟),1    OPENED  (未傳送),2 HEADERS_RECEIVED (已獲取響應頭),3    LOADING (正在下載響應體),4    DONE (請求完成)
            }
        };
 
        xhr.upload.addEventListener("progress", progressFunction, false);//新增上傳監聽器方法
        xhr.send(form);//傳送請求
    }
 
    function progressFunction(evt) {
 
        var progressBar = document.getElementById("progressactive");//獲取進度條物件
        var percentageDiv = document.getElementById("sr-only");//獲取展示進度資料物件
        if (evt.lengthComputable) {
            var max = evt.total;//檔案總大小
            var loaded = evt.loaded;//已上傳檔案大小
            console.log(max);
            progressBar.style.width = Math.round(loaded / max * 100) + "%";
            percentageDiv.innerHTML = Math.round(loaded / max * 100) + "%";
            if (evt.loaded == evt.total) {
                percentageDiv.innerHTML = "上傳完成";
            }
        }
 
    }
</script>
</html>

 

進度條progross實體檔案

public class Progress {
    private long bytesRead;
    private long contentLength;
    private long items;
    public long getBytesRead() {
        return bytesRead;
        }
    public void setBytesRead(long bytesRead) {
        this.bytesRead = bytesRead;
        }
    public long getContentLength() {
        return contentLength;
        }
    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
        }
    public long getItems() {
        return items;
        }
    public void setItems(long items) {
        this.items = items;
        }
    @Override
    public String toString() {
        return "Progress [bytesRead=" + bytesRead + ", contentLength=" + contentLength + ", items=" + items + "]";
        }
    }

 


監聽

package com.blue.util;

import org.apache.commons.fileupload.ProgressListener;

import com.blue.beans.ProgressInfo;

public class UploadListener implements ProgressListener {
    
    private static final long UPDATE_THRESHOLD = 35 * 1024L; // 20KB
    
    
    private long megaBytes = -1;

    private ProgressInfo pi = null;
    
    public UploadListener(ProgressInfo pi) {
        this.pi = pi;
    }

    public void update(long pBytesRead, long pContentLength, int pItems) {
        try{
            Thread.sleep(20);
        }catch(Exception ex){
            pi.setInProgress(false);
            ex.printStackTrace();
        }
        
        long mBytes = pBytesRead / UPDATE_THRESHOLD;
        if (megaBytes == mBytes && megaBytes > 0) {
            return;
        }
        
        megaBytes = mBytes;
        pi.setBytesRead(pBytesRead);
        pi.setFileIndex(pItems);
        pi.setTotalSize(pContentLength);
        
        if( pBytesRead + UPDATE_THRESHOLD >= pContentLength){
            pi.setCompleted(true);
            Util.info("UploadListener",pBytesRead + ";" + pItems + ";" + pContentLength);
            Util.info("UploadListener ->> update ","Completed");
        }
    }

}


controller

    @RequestMapping(value = "/html/project/upload.do", method = RequestMethod.POST)
                            public String upload(HttpServletRequest request,
                                    @RequestParam("file") MultipartFile[] file, ModelMap model) {
                                HttpSession session = request.getSession();
                                String token = (String) session.getAttribute("token");
                                String pa_id = request.getParameter("paid");
                                String type = request.getParameter("type");    //middle 中期成果  final 末期成功
                                String path = request.getSession().getServletContext()
                                        .getRealPath("upload");//獲取當前專案下的upload
                                for (int i = 0; i < file.length; i++) {
                                    
                                    String fileName = file[i].getOriginalFilename();//獲取檔名
                                    // String fileName = new Date().getTime()+".jpg";//替換新名字
                                    System.out.println(path);
                                    File targetFile = new File(path, fileName);//判斷檔案是否存在,不存在則建立,可建立資料夾
                                    if (!targetFile.exists()) {
                                        targetFile.mkdirs();
                                    }
                                    
                                    // 儲存
                                    try {
                                        //使用transferTo(dest)方法將上傳檔案寫到伺服器上指定的檔案。
                                        file[i].transferTo(targetFile);//此方法在上傳完成後才開始上傳
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                    // model.addAttribute("fileUrl", request.getContextPath() + "/upload/"
                                //     + fileName);
                                return "index";
                            }