好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

springmvc实现文件上传功能

一个简单的springmvc文件上传例子

所需的依赖

只需要这个就好了。在idea的依赖关系图中,commons-fileupload包含了commons-io依赖

?

1

2

3

4

5

< dependency >

   < groupId >commons-fileupload</ groupId >

   < artifactId >commons-fileupload</ artifactId >

   < version >1.3.2</ version >

</ dependency >

一个简单的文件上传的页面

?

1

2

3

4

< form action = "http://localhost:8080/springmvc_Web_exploded/fff" method = "post" enctype = "multipart/form-data" >

  < input type = "file" name = "file" id = "filer_input" multiple = "multiple" >

  < input type = "submit" value = "Submit" >

</ form >

在spring的配置文件中注入一个文件上传的bean

spring.xml

?

1

2

3

4

5

6

7

8

9

<!-- 文件上传的bean-->

  < bean id = "multipartResolver"

    class = "org.springframework.web.multipart测试数据mons.CommonsMultipartResolver" >

   <!--上传文件的最大大小,单位为字节 -->

   < property name = "maxUploadSize" value = "17367648787" ></ property >

 

   <!-- 上传文件的编码 -->

   < property name = "defaultEncoding" value = "UTF-8" ></ property >

</ bean >

实例代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

@PostMapping ( "/fff" )

  public String file( @PathVariable ( "file" )MultipartFile file, HttpServletRequest req) throws IOException {

 

  //判断文件不存在

   if (file.isEmpty()){

    return "faile.html" ;

   }

 

   //我想放到这个地方文件的路径

   String realPath = req.getServletContext().getRealPath( "/WEB-INF/file" );

   //返回客户端文件系统中的原始文件名

   String filename = file.getOriginalFilename();

   File myFile = new File(realPath, filename);

   if (!myFile.getParentFile().exists()){

    myFile.getParentFile().mkdir();

    System.out.println( "文件夹被创建了" );

   }

 

  //将前端传过来的文件,传到自己new的File对象中

   file.transferTo(myFile);

 

   return "success.html" ;

  }

注意事项:

1、文件上传请求必须用 post 请求。
2、注意路径问题
3、前端的 form表单 必须添加 enctype="multipart/form-data" 这个属性

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/zhihu_0/article/details/114821331

查看更多关于springmvc实现文件上传功能的详细内容...

  阅读:15次