文件上传
开发Web应用时,文件上传是常见的需求,浏览器通过表单形式将文件以流的形式传递给服务器,服务器在对上传的数据解析处理。
<!DOCTYPE html>
// 导入Thymeleaf配置
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>动态添加文件上传列表</title>
// 导入相关CSS配置文件 login为static文件夹下的文件,见静态文件导入
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<script th:src="@{/login/js/jquery.min.js}"></script>
</head>
<body>
<div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}">上传成功</div>
<form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">
上传文件: <input type="button" value="添加文件" onclick="add()"/>
<div id="file" style="margin-top: 10px;" th:value="文件上传区域"> </div>
<input id="submit" type="submit" value="上传"
style="display: none;margin-top: 10px;"/>
</form>
<script type="text/javascript">
function add(){
var innerdiv = "<div>";
innerdiv += "<input type='file' name='fileUpload' required='required'>" +
"<input type='button' value='删除' οnclick='remove(this)'>";
innerdiv +="</div>";
$("#file").append(innerdiv);
$("#submit").css("display","block");
}
function remove(obj) {
$(obj).parent().remove();
if($("#file div").length ==0){
$("#submit").css("display","none");
}
}
</script>
</body>
</html>
# Thymeleaf页面缓存设置(默认为true),开发中为方便调试应设置为false,上线稳定后保持默认true
spring.thymeleaf.cache=false
# 配置国际化文件基础名
spring.messages.basename=i18n.login
# 单个上传文件大小显示(默认1MB)
spring.servlet.multipart.max-file-size=10MB
# 总上传文件大小限制(默认为10MB)
spring.servlet.multipart.max-request-size=50MB
@Controller
public class FileController {
@GetMapping("/toUpload")
public String toUpload(){
return "upload";
}
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile[] fileUpload, Model model){
model.addAttribute("uploadStatus","上传成功!");
for(MultipartFile file: fileUpload){
String fileName = file.getOriginalFilename();
fileName = UUID.randomUUID()+"_"+fileName;
String dirPath = "F:/file/";
File filePath = new File(dirPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try{
file.transferTo(new File(dirPath+fileName));
}catch (Exception e){
e.printStackTrace();
model.addAttribute("uploadStatus","上传失败:"+e.getMessage());
}
}
return "upload";
}
}
文件下载
- 下载文件能够通过IO流实现,所以多数框架并没有对文件下载进行封装处理。文件下载时设计不同浏览器的解析处理,可能会出现中文乱码的情况。
-
英文名文件下载
-
添加文件下载工具依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<div style="margin-bottom: 10px">文件下载列表:</div>
<table>
<tr>
<td>xxxxx</td>
//文件下载前需要保证文件下载目录中存在文件 xxxxx 自行存放
<td><a th:href="@{/download(filename='xxxxx')}">下载文件</a></td>
</tr>
<tr>
<td>xxxxx</td>
<td><a th:href="@{/download(filename='xxxxx')}">
下载文件</a></td>
</tr>
</table>
</body>
</html>
@GetMapping("/toDownload")
public String toDownload(){
return "download.html";
}
@GetMapping("/download")
public ResponseEntity<byte[]> fileDownload(String filename){
String dirPath = "F:/file/";
File file = new File(dirPath+File.separator+filename);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try{
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
}
}
- 效果测试即可
-
中文名文件下载
- 对于上部分代码测试,如果要下载的文件为一中文名文件,中文名称会变成"_",需要进行编码乱码设置
-
添加处理中文编码的代码
@GetMapping("/toDownload")
public String toDownload(){
return "download.html";
}
@GetMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws Exception{
String dirPath = "F:/file/";
File file = new File(dirPath+File.separator+filename);
HttpHeaders headers = new HttpHeaders();
filename = getFilename(request,filename);
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try{
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
}
}
private String getFilename(HttpServletRequest request,String filename) throws Exception{
String[] IEBrowserKeyWords = {"MSTE","Trident","Edge"};
String userAgent = request.getHeader("User-Agent");
for(String keyWord:IEBrowserKeyWords){
if(userAgent.contains(keyWord)){
return URLEncoder.encode(filename,"UTF-8").replace("+"," ");
}
}
return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}