SpringMVC使用MultipartResolver实现文件上传

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringMVC使用MultipartResolver实现文件上传

loli_kong   2023-03-23 我要评论

SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文

件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可。

MultipartResolver 的实现类有两个:

  • CommonsMultipartResolver
  • StandardServletMultipartResolver

两个的区别:

  • 第一个需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的servlet 版本中使用。
  • 第二个不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在Servlet 3 以上的版本使用。

我们这里使用第一种来实现上传。

1.导入依赖

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

2.再application中添加配置

<!-- 多部分文件上传 -->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="maxUploadSize" value="104857600"/>
    <property name="maxInMemorySize" value="4096"/>
</bean>

**maxUploadSize:**设置允许上传文件的最大值,以字节为单位。默认为-1,表示无限制。

**defaultEncoding:**表示用来请求解析request请求的默认编码格式,当没有指定时默认使用ISO-8859-1。当request自己指明了他的编码格式的时候就会忽略这里的defaultEncoding。

3.编写controller代码

    @Autowired
    private HttpServletRequest request;
    @PostMapping("native")
    public String nativeUpload(@RequestParam("file") MultipartFile file, String folder) throws UnsupportedEncodingException {
        // 拿到webapp下面img文件夹的位置
        String path = request.getSession().getServletContext().getRealPath("img");
        // getOriginalFilename获取文件的原始名称,例如:2.jpg
        String filePath = path + "\\" + file.getOriginalFilename();
        File destFile = new File(filePath);
        // 如果目录不存在
        if (!destFile.getParentFile().exists()) {
            // 创建目录(可能位多层)
            destFile.mkdirs();
        }
        // destFile:目标文件
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String res = "http://localhost:9101/img/" + file.getOriginalFilename();
        return new String(res.getBytes(), "UTF-8");
    }

这里MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们