SpringBoot入门学习(十六)~~文件上传

目录

 

SpringBoot中的文件上传

一、上传代码

二、上传相关参数配置


SpringBoot中的文件上传

       以前,我们使用SpringMVC上传文件的时候,需要引入commons-fileupload.jar和commons-io.jar。在web.xml中配置文件上传解析器。

现在在SpringBoot中仍然使用MultipartFile上传,但是使用的是Servlet3中的Part对象完成上传,而不是fileUpload。因此的话,不需要引入额外的包。

  • 一、上传代码

因为应用是打成jar包,需要把上传的文件放在其他的位置,通过设置spring.resources.static-locations来完成资源的映射。

1、在配置文件中,定义文件上传的路径

file.path=F:/upload/

   2、编写简单的静态页面

<!DOCTYPE html>

  <html lang="en">

  <head>

    <meta charset="UTF-8">

    <title>Title</title>

  </head>

  <body>

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

        <input type="file" name="file">

        <input type="submit" value="提交">

    </form>

  </body>

  </html>

 

   3、编写upload控制器

@Controller

  public class FileUploadController {

   @Value("${file.path}")

   private String filePath;

  

   @RequestMapping("/upload")

   @ResponseBody

   public String upload(MultipartFile file) throws Exception{

      String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

      String fileName = UUID.randomUUID().toString() + extName;

      FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(new File(filePath+fileName)));

      return fileName;

   }

}

 

   4、启动项目~测试上传

 

 

 

二、上传相关参数配置

#是否允许处理上传

spring.http.multipart.enabled=true

#允许最大的单文件上传大小

spring.http.multipart.max-file-size=1MB

#允许的最大请求大小

spring.http.multipart.max-request-size=10MB

 

也可以通过创建MultipartConfigElement类型的bean对上传进行配置。

 

@Bean

  public MultipartConfigElement multipartConfigElement(){

   MultipartConfigFactory multipartConfigElement =  new MultipartConfigFactory();

   multipartConfigElement.setMaxFileSize("1MB");

   multipartConfigElement.setMaxRequestSize("10MB");

   return multipartConfigElement.createMultipartConfig();

}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值