springboot文件上传

使用springboot实现文件上传功能
springboot版本:2.0.8.RELEASE

相关依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

配置上传文件相关属性

默认上传的文件为1M,大于1M时,上传会报错文件太大的错误,在 application.properties 中设置上传文件的参数即可

1
2
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

上传页面

在 src/main/resources 的templates目录中新建一个 upload.ftl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<title>uploadimg.html</title>

<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta name="description" content="this is my page"></meta>
<meta name="content-type" content="text/html; charset=UTF-8"></meta>

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

</head>

<body>
<form enctype="multipart/form-data" method="post" action="testuploadimg">
图片<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

controller相关方法

在 controller 中写两个方法,一个方法跳转到上传文件的页面,一个方法处理上传文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 //跳转到上传文件的页面
@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
public String goUploadImg(HttpServletRequest request) {
//跳转到 templates 目录下的 uploadimg.html

return "upload";
}

//处理文件上传
@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
// String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
String filePath = "D:\\workSpace\\IntellijWorkspace\\contentsales\\src\\main\\resources\\static\\imgupload\\";
System.out.println(filePath);
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return "uploadimg success";
}

工具类 FileUtil

工具类 FileUtil 的 uploadFile 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.dxysun.contentsales.utils;

import java.io.File;
import java.io.FileOutputStream;

public class FileUtil {

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}

参考

springboot实现文件上传

打赏

请我喝杯咖啡吧~

支付宝
微信