一直有小夥伴不知道springboot項目的檔案上傳功能,今天我們就來搞懂它,讀完本篇文章你可以知道以下内容
- 單個檔案上傳
- 多個檔案上傳
- 檔案與form表單普通屬性同時送出
- 通過ajax送出form表單(含檔案上傳 )
- 檔案下載下傳(解決中文檔案名亂碼)
首先來看前端html,一個頁面中同時實作了ajax方式送出表單(含附件)以及通過submit方式進行表單送出(帶附件)
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="/webjars/jquery/3.5.1/jquery.js"></script>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var uploadFile = function () {
var formdata = new FormData(document.getElementById("forms"));
console.log(formdata);
$.ajax({
url:"/upload",
type: "POST",
data: formdata,
processData:false,
contentType:false,
success:function(){
console.log("over...");
},
error: function (e) {
alert("錯誤")
}
})
}
</script>
</head>
<body>
<div class="container">
<form class="form-signin" id="forms" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<h2 class="form-signin-heading">個人資訊</h2>
<input type="hidden" th:id="${person.id}" name="id" th:value="${person.id}"/>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">使用者名</span>
<input type="text" class="form-control" placeholder="使用者名" id="userName" name="userName" th:value="${person.userName}" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">年 齡</span>
<input type="text" class="form-control" placeholder="age" id="age" name="age" th:value="${person.age}" aria-describedby="basic-addon1">
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">手機号</span>
<input type="text" class="form-control" placeholder="mobile" id="mobile" name="mobile" th:value="${person.mobile}" aria-describedby="basic-addon1">
</div>
<div class="form-group">
<label for="file">上傳附件</label>
<input type="file" id="file" name="file" >
<p class="help-block">Example block-level help text here.</p>
</div><div class="form-group">
<label for="files">上傳多附件</label>
<input type="file" id="files" name="files" multiple>
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary btn-default" id="upload" onclick="uploadFile()">ajax上傳</button>
<button type="submit" class="btn btn-primary btn-default" id="" >submit上傳</button>
</div>
</form>
</div> <!-- /container -->
</body>
</html>
後端代碼:
package com.myproject.springmybatis.controller;
import com.myproject.springmybatis.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
public class FileUploadController {
@GetMapping("/upload")
public String toUpload(ModelMap map){
Person person = new Person();
person.setPassword("!23456");
person.setAge(18);
person.setId(1L);
person.setUserName("zhangsan");
map.put("person", person);
return "fileUpload";
}
@PostMapping("/upload")
@ResponseBody
public Map<String,Object> upload(Person person, @RequestParam("file") MultipartFile file,@RequestParam("files") MultipartFile[] files) throws IOException {
Map<String,Object> map = new HashMap<>();
String filePath = "/Users/xumingfei/Desktop/test/";
System.out.println(person);
if (!file.isEmpty()) {
String contentType = file.getContentType();
String filename = file.getOriginalFilename();
file.transferTo(new File(filePath+filename));
map.put("msg","上傳單個成功");
}else {
map.put("msg","上傳失敗");
}
for (MultipartFile f :
files) {
String fname = f.getOriginalFilename();
f.transferTo(new File(filePath+fname));
System.out.println(f.getOriginalFilename());
}
map.put("msg1","上傳多個附件成功");
return map;
}
/**
* 檔案下載下傳
* @param request
* @param response
* @param fileName
* @return
* @throws IOException
*/
@RequestMapping("/downloadFile")
@ResponseBody
public String download(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
if (StringUtils.isEmpty(fileName)) {
fileName = "test附件.doc";
}
if (fileName != null) {
File file = new File("/Users/xumingfei/Desktop/test/"+fileName);
if (file.exists()){
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏覽器的處理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setContentType("application/force-download");
response.addHeader("Content-Disposition","attachment;fileName="+fileName);
byte[] buffer = new byte[1024];
FileInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
inputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream os = response.getOutputStream();
int i = bufferedInputStream.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bufferedInputStream.read(buffer);
}
return "download success";
} catch (Exception e) {
e.printStackTrace();
}finally {
bufferedInputStream.close();
inputStream.close();
}
}
}
return "failure";
}
}
大家喜歡的話不妨給小編點個贊吧!掃一掃關注公衆号不迷路。