SpringBoot:SpringMVC檔案上傳及Ajax非同步
阿新 • • 發佈:2018-12-10
一、使用Spring框架中的MultipartFile實現後臺程式碼邏輯處理
1. MultipartFile API 如下:
2. 後臺邏輯程式碼
@Controller
public class FileUploadController {
//檔案上傳
@ResponseBody
@RequestMapping(value="/fileUpload",method=RequestMethod.POST)
public String fileUpload(@RequestParam("file")MultipartFile multFile,HttpServletRequest request) {
//獲取上傳檔名並列印
String multFileName = multFile.getOriginalFilename();
System.out.println("檔名為:"+multFileName);
//獲取上傳檔案大小並列印
long size = multFile.getSize();
System.out.println("檔案大小:"+size);
//*. 更改檔名:命名規則+時間
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SS" );
String times = simpleDateFormat.format(new Date());
//獲取檔案字尾
String suffix = multFileName.substring(multFileName.lastIndexOf("."));
System.out.println("檔案字尾名"+suffix);
//**. 檔案內容讀取
try {
InputStream inputStream = multFile.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"GBK");
char[] chars = new char[1024];
int len = inputStreamReader.read(chars);
String context = new String(chars,0,len);
System.out.println("文字內容是:"+context);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//***. 檔案上傳(主要)
String path = "E:/FileUpload";
File newFile = new File(path+"/"+times+suffix);
if(!newFile.getParentFile().exists()) { //判斷檔案父目錄是否存在
newFile.getParentFile().mkdirs();
}
try {
multFile.transferTo(newFile);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "上傳成功";
}
//首頁
@RequestMapping("/")
public String toIndex() {
return "index";
}
}
二、前端程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>檔案上傳下載測試</title>
<script src="${request.contextPath}/js/jquery-1.12.4.min.js"></script>
</head>
<body>
<div style="width: 100%;margin: 0 20% ;display: flex; flex-direction: column; width: 200px; ">
<h1>檔案上傳</h1>
<form id="uploadForm" action="${request.contextPath}/fileUpload" method="POST" enctype="multipart/form-data">
<input id="file" type="file" name="file"/>
<input type="text" name="text1" />
<input type="text" name="text2" />
<div style="margin-top: 10px;">
<input type="submit" value="直接上傳"/>
<button type="button" id="ajaxBtn">ajax後臺上傳</button>
</div>
</form>
<h1>檔案下載</h1>
<script type="text/javascript">
$("#ajaxBtn").on('click',function(){
console.log("ajaj非同步檔案上傳開始---");
//使用 HTML5 FormData物件; 使用js原生物件
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url:'${request.contextPath}/fileUpload' ,
type:'POST',
data:formData ,
cache: false ,
contentType:false ,
processData:false ,
success:function(data){
console.log("ajax返回值"+data);
}
});
});
</script>
</div>
</body>
</html>