spring boot 的文件上传

spring boot 的文件上传与 spring mvc 的文件上传基本一致,只需注意一些配置即可。 

1).引入thymeleaf,支持页面跳转

<!-- 添加thymeleaf -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>uploadimg.html</title>
        <meta name="content-type" content="text/html; charset=UTF-8"/>
    </head>
    <body>
        <form action="/testuploadimg" method="post" enctype="multipart/form-data">
            图片<input type="file" name="file"/>
            <input type="submit" value="上传"/>
        </form>
    </body>
</html>

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

//跳转到上传文件的页面 
@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)
public String goUploadImg(){
    //跳转到 templates 目录下的 uploadimg.html 
    return "uploadimg";
}

// 处理文件上传 
@RequestMapping(value="/testuploadimg", method = RequestMethod.POST) 
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request){
   String fileName = file.getOriginalFilename();
   String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
  file.transferTo(filePath+fileName);  
   // 返回json 
   return "uploadimg success";
}

4).在浏览器输入 :http://localhost:8080/gouploadimg 测试

  上传文件后,在应用的 src/main/webapp/imgupload 目录下

5).如果上传的文件大于 1M 时,上传会报错文件太大的错误,在 application.properties 中设置上传文件的参数即可

  spring.http.multipart.maxFileSize=100Mb

  spring.http.multipart.maxRequestSize=100Mb

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值