springBoot上传文件

需要实现该文章功能:springboot 添加静态资源映射(WebMvcConfigurer)

介绍

springboot上传文件,是通过 commons-fileupload.jar、commons-io.jar 实现的,但是对其做了封装,使用起来更简单

Controller方法中,通过 MultipartFile 接口来处理文件上传

修改pom.xml

添加 commons-fileupload、commons-io 依赖:

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

html

<form method="post" enctype="multipart/form-data" action="/upload">
    上传图片:<input type="file" name="image"><br>
    <input type="submit">
</form>

注意

  • method="post" 必须是 post 方法

  • enctype="multipart/form-data":enctype 是表单请求正文的类型,上传文件必须设置

  • <input type="file" name="image">:上传文件控件,注意名字

设置临时路径

上传文件时,Servlet容器(如tomcat)会将 正在接收的文件 (该文件后缀一般为 .tmp) 保存到一个 临时路径 中。

注意: 启动springboot时,会 自动创建该临时目录

该临时路径与操作系统相关,取默认值时,该路径可能会被删除

方式一:修改 application.properties

通过配置文件进行修改:

spring.servlet.multipart.location=${file.upload}

解释: ${file.upload} 取《springboot 添加静态资源映射(WebMvcConfigurer)》文中 file.upload 配置的值

方式二:修改 application.yml

通过配置文件进行修改:

spring:
  servlet:
    multipart:
      location: ${file.upload}

解释: ${file.upload} 取《springboot 添加静态资源映射(WebMvcConfigurer)》文中 file.upload 配置的值

方式三

通过配置类进行修改:

@Configuration
public class UploadConfig {
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(uploadFolder);
        return factory.createMultipartConfig();
    }
}

MultipartFile接口

springboot 将上传文件的相关数据封装到 MultipartFile 接口类对象中,主要方法:

  • isEmpty():是否上传文件

  • getOriginalFilename():上传文件名称

  • transferTo():将临时文件转移到指定目录

  • getContentType():获取类型

  • getInputStream():获取输入流

  • getSize():获取上传文件大小

  • getBytes():获取上传文件的字节数组

  • getName():获取临时文件名

java代码

@RestController
@RequestMapping("/upload")
public class UploadCtrl {

    @Value("${file.upload}")
    private String upload;
    //在 springboot 添加静态资源映射(WebMvcConfigurer) 文中配置此项
    @Value("${file.url}")
    private String fileUrl;

    @PostMapping("/upload")
    public JsonResult upload(MultipartFile image,HttpServletRequest req) {
        JsonResult<Map<String, String>> jr=new JsonResult();

        String oFilename=image.getOriginalFilename();
        String suffix=oFilename.substring(oFilename.lastIndexOf("."));
        String newFilename=UUIDTools.randomUUID()+suffix;

        //前台页面回显图片的url
        String imageURL=fileUrl+newFilename;

        File file=new File(upload);
        //由于设置的临时目录也是该目录,启动服务时,会自动创建临时目录,所以此处可以不用判断
        if(!file.exists()) {
            file.mkdirs();
        }
        File filePath=new File(file,newFilename);

        try {
            image.transferTo(filePath);
            jr.setCode(0);

            Map<String, String> map=new HashMap<String, String>();
            map.put("imageURL", imageURL);//页面回显图片
            map.put("dbURL", imageURL);//保存到数据库的url
            jr.setData(map);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return jr;
    }
}

原文出处:/show_1IXcREBG7ME.html