spring 6.x

spring 6.x文件上传问题

由于spring 6.x版本 删除了commons包导致没有CommonsMultipartResolver类但是spring mvc 6.x提供了一个文件上传的MultipartFile接口

controller控制器

@ResponseBody
@RequestMapping(value = "file.load",produces = "text/html;charset=UTF-8")
public String easyUploadFile(@RequestParam("fileLoad") MultipartFile file, HttpServletRequest request) {
    try {
        String originalFilename = file.getOriginalFilename();
        System.out.println("文件名=" + originalFilename);
        //得到服务器文件夹地址,准备创建文件夹
        String realPath = request.getServletContext().getRealPath("") + "uploadImg";
        File file1 = new File(realPath);
        if (!file1.exists()) {
            System.out.println("文件夹不存在,开始创建");
            file1.mkdir();
        }
        System.out.println("文件夹名=" + realPath);
        //保存文件
        file.transferTo(new File(realPath,originalFilename));
    } catch (IOException e) {
        System.err.println(e);
        return "文件上传失败";
    }
    return "文件上传成功";
}

需要在web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
<!--       MultipartFile核心配置     -->
        <multipart-config>
<!--         上传文件最大多少   -->
            <max-file-size>10485760</max-file-size>
<!--         最大请求大小   -->
            <max-request-size>10485760</max-request-size>
<!--         多大以上的文件可以上传   -->
            <file-size-threshold>0</file-size-threshold>
        </multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

html

<%-- 文件上传必须的有的属性 enctype="multipart/form-data" --%>
<form action="${pageContext.request.contextPath}/file.load" method="post" enctype="multipart/form-data">
    <input type="file"  name="fileLoad">
    <input type="submit" value="文件上传">
form>

你可能感兴趣的:(spring,servlet,java)