1. 程式人生 > >簡單實現SpringMVC+ajax顯示進度

簡單實現SpringMVC+ajax顯示進度

  1. 使用Spring自帶的MultiPartResolver,在spring-mvc.xml檔案中加上
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000" />
        <property name="maxInMemorySize" value="514" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="uploadTempDir" value="upload/temp" />
</bean>
2.在controller中使用 transferTo來寫入檔案
@RequestMapping("/upload")
	public void uploadFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") CommonsMultipartFile file) throws IOException {
		
	      String path="D:\\"+new Date().getTime()+file.getOriginalFilename();
	      System.out.println("檔案原始名稱="+file.getOriginalFilename());
	      File newFile=new File(path);
	      //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
	      file.transferTo(newFile);
	}
3.前端使用原生ajax來實現
<%@ page language="java" import="java.util.*" pageEncoding="Utf-8"%>  
<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
%>  
  
<!DOCTYPE html>  
<html>  
<head>  
<base href="<%=basePath%>">  
  
  
<meta http-equiv="pragma" content="no-cache">  
<meta http-equiv="cache-control" content="no-cache">  
<meta http-equiv="expires" content="0">  
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
<meta http-equiv="description" content="This is my page">  
<!-- 
 <link rel="stylesheet" type="text/css" href="styles.css"> 
-->  
<link href="assets/css/bootstrap.min.css" rel="stylesheet">  
  
<style type="text/css">  
.file-box {  
    position: relative;  
    width: 340px  
}  
  
.txt {  
    height: 22px;  
    border: 1px solid #cdcdcd;  
    width: 180px;  
    vertical-align: middle;  
    margin: 0;  
    padding: 0  
}  
  
.btn {  
    border: 1px solid #CDCDCD;  
    height: 24px;  
    width: 70px;  
    vertical-align: middle;  
    margin: 0;  
    padding: 0  
}  
  
.file {  
    position: absolute;  
    top: 0;  
    right: 80px;  
    height: 24px;  
    filter: alpha(opacity :   0);  
    opacity: 0;  
    width: 260px;  
    vertical-align: middle;  
    margin: 0;  
    padding: 0  
}  
</style>  
<script type="text/javascript">  
    function UpladFile() {  
        var fileObj = document.getElementById("file").files[0]; // js 獲取檔案物件  
        var FileController = "test/upload"; // 接收上傳檔案的後臺地址   
        // FormData 物件---進行無重新整理上傳  
        var form = new FormData();  
        form.append("author", "hooyes"); // 可以增加表單資料  
        form.append("file", fileObj); // 檔案物件  
        // XMLHttpRequest 物件  
        var xhr = new XMLHttpRequest();  
        xhr.open("post", FileController, true);  
        xhr.onload = function() {  
            alert("上傳完成!");  
            //$('#myModal').modal('hide');  
        };  
                //監聽progress事件  
        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)  
                    + "%";  
  
        }  
  
    }  
</script>  
  
</head>  
  
<body style="width: 80%;height: 80%;margin: 0px auto;">  
    <div class="row bootstrap-admin-no-edges-padding">  
        <div class="col-md-12">  
            <div class="panel panel-default">  
                <div class="panel-heading">  
                    <div class="text-muted bootstrap-admin-box-title">檔案管理</div>  
                </div>  
                <div class="bootstrap-admin-panel-content">  
                    <button class="btn btn-primary btn-lg" data-toggle="modal"  
                        data-target="#myModal">上傳</button>  
                    <input type="text" id="test">  
                </div>  
            </div>  
        </div>  
    </div>  
  
    <!-- 模態框(Modal) -->  
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog"  
        aria-labelledby="myModalLabel" aria-hidden="true">  
        <div class="modal-dialog">  
            <div class="modal-content">  
                <div class="modal-header">  
                    <button type="button" class="close" data-dismiss="modal"  
                        aria-hidden="true">×</button>  
                    <h4 class="modal-title" id="myModalLabel">檔案上傳進度</h4>  
                </div>  
                <div class="modal-body">  
                    <progress id="progressBar" value="0" max="100"  
                        style="width: 100%;height: 20px; "> </progress>  
                    <span id="percentage" style="color:blue;"></span> <br>  
                    <br>  
                    <div class="file-box">  
                        <input type='text' name='textfield' id='textfield' class='txt' />  
                        <input type='button' class='btn' value='瀏覽...' /> <input  
                            type="file" name="file" class="file" id="file" size="28"  
                            onchange="document.getElementById('textfield').value=this.value" />  
                        <input type="submit" name="submit" class="btn" value="上傳"  
                            onclick="UpladFile()" />  
                          
                    </div>  
                </div>  
                <div class="modal-footer">  
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉  
                    </button>  
                </div>  
            </div>  
            <!-- /.modal-content -->  
        </div>  
        <!-- /.modal -->  
    </div>  
    <script type="text/javascript"  
        src="http://code.jquery.com/jquery-2.0.3.min.js"></script>  
    <script src="assets/js/bootstrap.min.js"></script>  
</body>  
</html>