springboot实现文件上传

1.创建项目,添加依赖

[XML]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<!--配置父级工程-->

<`parent`>

<`groupId>org.springframework.boot</groupId`>

<`artifactId>spring-boot-starter-parent</artifactId`>

<`version>2.0.3.RELEASE</version`>

</`parent`>

<!--配置WEB启动器 SpringMVC、Restful、jackson-->

<`dependencies`>

<`dependency`>

<`groupId>org.springframework.boot</groupId`>

<`artifactId>spring-boot-starter-web</artifactId`>

</`dependency`>

<!--配置springboot热部署-->

<`dependency`>

<`groupId>org.springframework.boot</groupId`>

<`artifactId>spring-boot-devtools</artifactId`>

</`dependency`>

<!--添加thymeleaf-->

<`dependency`>

<`groupId>org.springframework</groupId`>

<`artifactId>spring-boot-starter-thymeleaf</artifactId`>

</`dependency`>

</`dependencies`>

<!--配置全局属性-->

<`properties`>

<!--配置jdk版本-->

<`java.version>1.8</java.version`>

</`properties`>

<!--配置maven插件-->

<`build`>

<`plugins`>

<`plugin`>

<`groupId>org.springframework.boot</groupId`>

<`artifactId>spring-boot-maven-plugin</artifactId`>

</`plugin`>

</`plugins`>

</`build`>

2.在 src/main/resources 目录下新建 static 目录和 templates 目录。 static存放静态文件,比如 css、js、image… templates 存放静态页面。先在templates 中新建一个 uploadimg.html

[HTML]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

<!DOCTYPE html>

<`html`>

<`head`>

<`title>uploadFiles.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`>

</`head`>

<`body`>

<`form enctype="multipart/form-data" method="post" action="/testuploadimg"`>

图片<`input type="file" name="file"`/>

<`input type="submit" value="上传图片"`/>

</`form`>

</`body`>

</`body`>

</`html`>

3.在resources文件夹下面增加配置文件application.properties,设置静态资源路径

[XML]纯文本查看__复制代码

?

1

spring.resources.staticLocations=classpath:/static/,classpath:/templates/

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

[Java]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

@GetMapping`("/toUpload")`

public String turnToUploadHtml(){

return  "/html/uploadFiles.html"`;`

}

@RequestMapping`(value="/testuploadimg", method = RequestMethod.POST)`

public @ResponseBody

String uploadImg(`@RequestParam("file"`) MultipartFile file,

HttpServletRequest request) {

String contentType = file.getContentType();

String fileName = file.getOriginalFilename();

String filePath = request.getSession().getServletContext().getRealPath(`"imgupload/"`);

try {

FileUtil.uploadFile(file.getBytes(), filePath, fileName);

} catch (Exception e) {

e.printStackTrace();

}

//返回json

return "success"`;`

}

5.测试
地址:http://localhost:8080/toUpload

评论

暂无评论