1. 相關依賴 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <groupId>io.gitee.liubin0509</groupId> <artifactId>study</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </dependency> </dependencies> </project>
2. 畫面 upload.ftl
<!DOCTYPE html> <html> <head> <script src="./js/jquery.min.js"></script> </head> <body> <h1>Spring Boot file upload example</h1> <form id="FileuploadForm" method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="uploadFile" id="uploadFile"/><br /> <br /> <input type="button" value="上傳文件" onclick="upload()" /> <div id="msg"></div> </form> <!--進度條部分(默認隱藏)--> <div style="display: none;" class="progress-body"> <div> <span style="width: 100px; display: inline-block; text-align: right">上傳進度:</span> <progress></progress><percentage>0%</percentage> </div> <div> <span style="width: 100px; display: inline-block; text-align: right">上傳速度:</span> <span style="margin-bottom: 10px; margin-left: 30px; width: 300px;" class="progress-speed">0 M/S, 0/0M</span> </div> <div> <span style="width: 100px; display: inline-block; text-align: right">上傳狀態:</span> <span style="margin-bottom: 10px; margin-left: 30px; width: 300px;" class="progress-info">請選擇文件並點擊上傳文件按鈕</span> </div> </div> </body> </html>
3, 上傳ajax
<script>
// 上傳文件
function upload(){
$("#msg").text("");
var checkFile = $("#uploadFile").val();
var msgInfo = "";
if(null==checkFile || ""==checkFile){
$("#msg").text("文件為空,請選擇文件!");
}else{
var formData = new FormData(document.getElementById("FileuploadForm"));
$.ajax({
type: "POST",
enctype:'multipart/form-data',
url: '/upload',
data: formData,
cache:false,
processData:false,
contentType:false,
error:function(result){
console.log("error");
console.log(result);
flag = false;
$("#msg").text("訪問服務器錯誤,請重試!");
},
success: function(result){
console.log("success");
},
xhr: function () {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
//處理進度條的事件
xhr.upload.addEventListener("progress", progressHandle, false);
//加載完成的事件
xhr.addEventListener("load", completeHandle, false);
//加載出錯的事件
xhr.addEventListener("error", failedHandle, false);
//加載取消的事件
xhr.addEventListener("abort", canceledHandle, false);
//開始顯示進度條
showProgress();
return xhr;
}
}
}, 'json');
}
}
var start = 0;
//顯示進度條的函數
function showProgress() {
start = new Date().getTime();
$(".progress-body").css("display", "block");
}
//隱藏進度條的函數
function hideProgress() {
$("#uploadFile").val('');
$('.progress-body .progress-speed').html("0 M/S, 0/0M");
$('.progress-body percentage').html("0%");
$('.progress-body .progress-info').html("請選擇文件並點擊上傳文件按鈕");
//$(".progress-body").css("display", "none");
}
//進度條更新
function progressHandle(e) {
$('.progress-body progress').attr({value: e.loaded, max: e.total});
var percent = e.loaded / e.total * 100;
var time = ((new Date().getTime() - start) / 1000).toFixed(3);
if(time == 0){
time = 1;
}
$('.progress-body .progress-speed').html(((e.loaded / 1024) / 1024 / time).toFixed(2) + "M/S, " + ((e.loaded / 1024) / 1024).toFixed(2) + "/" + ((e.total / 1024) / 1024).toFixed(2) + " MB. ");
$('.progress-body percentage').html(percent.toFixed(2) + "%");
if (percent == 100) {
$('.progress-body .progress-info').html("上傳完成,后台正在處理...");
} else {
$('.progress-body .progress-info').html("文件上傳中...");
}
};
//上傳完成處理函數
function completeHandle(e) {
$('.progress-body .progress-info').html("上傳文件完成。");
setTimeout(hideProgress, 2000);
};
//上傳出錯處理函數
function failedHandle(e) {
$('.progress-body .progress-info').html("上傳文件出錯, 服務不可用或文件過大。");
};
//上傳取消處理函數
function canceledHandle(e) {
$('.progress-body .progress-info').html("上傳文件取消。");
};
</script>
4. css
<style type="text/css"> progress { background-color: #56BE64; } progress::-webkit-progress-bar { background: #ccc; } progress::-webkit-progress-value { background: #56BE64; } percentage{ position: fixed; left: 160px; } </style>
5. controller
package io.gitee.liubin0509.study.web.ctrl; import java.io.File; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import io.gitee.liubin0509.study.web.bean.InfoMsg; @Controller @RequestMapping("/upload") public class UploadCtrl { private static final String TMP_PATH = "e:/projects/tmp"; @RequestMapping(value = "", method = RequestMethod.GET) public String fileUploadInit() { // InfoMsg infoMsg = new InfoMsg(); return "upload"; } @RequestMapping(value = "", method = RequestMethod.POST) @ResponseBody public InfoMsg fileUpload(@RequestParam("uploadFile") MultipartFile file) { InfoMsg infoMsg = new InfoMsg(); if (file.isEmpty()) { infoMsg.setCode("error"); infoMsg.setMsg("Please select a file to upload"); return infoMsg; } try { File tmp = new File(TMP_PATH, file.getOriginalFilename()); if(!tmp.getParentFile().exists()){ tmp.getParentFile().mkdirs(); } file.transferTo(tmp); infoMsg.setCode("success"); infoMsg.setMsg("You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { infoMsg.setCode("error"); infoMsg.setMsg("Uploaded file failed"); } return infoMsg; } }
6. springboot 配置
pom文件中引用 不同版本的springboot,上傳文件大小配置不一樣
#spring.resources.static-locations=classpath:/static/ spring.freemarker.template-loader-path=classpath:/static/ # for SpringBoot 1.3.x or earlier multipart.maxFileSize=300MB multipart.maxRequestSize=300MB # Spring Boot 1.4.x and 1.5.x spring.http.multipart.maxFileSize=300MB spring.http.multipart.maxRequestSize=300MB #Spring Boot 2.x spring.servlet.multipart.maxFileSize=300MB spring.servlet.multipart.maxRequestSize=300MB
源碼下載地址: https://gitee.com/liubin0509/spring-uploadfile
