Spring MVC实现MultipartFile文件上传功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/83859469

前端

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>修改信息</title>
</head>
<body>
    <form action="/shop/updateUserinfo" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>请选择头像:</td>
                <td><input type="file" name="image" /></td>
            </tr>
            <tr>
                <td><input type="submit" name="submit" value="提交"/></td>
                <td><input type="reset" name="reset" value="重置"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

注意:
1.文件选择标签type=“file”
2.要定义enctype=“multipart/form-data”,以二进制流传输,否则Spring MVC解析失败
3.文件提交以POST请求为主


后台

控制器实现

@RequestMapping(value = "/updateUserinfo", method = RequestMethod.POST)
@ResponseBody
public String updateUserinfo(MultipartFile file) throws IOException {
	// file是通过Spring MVC自动映射HTTP请求同名参数获取的
    if (!file.isEmpty()) {
        // 得到的是参数名 image
        log.info(file.getName());
        // 得到的是图片原来的名字如:1234.png
        log.info(file.getOriginalFilename());
        log.info(file.getSize());
        // 要保存图片到的路径和名字
        String imageUrl = "/home/lin/" +  "store.png";
        // 将上传文件保存到相应位置
        file.transferTo(new File(imageUrl());
    }
    return "";
}

MultipartFile是一个Spring MVC提供的一个类,因此还需要相应的解析器----MultipartResolver

MultipartResolver配置

MultipartResolver只是一个接口, 它有两个实现类

  1. CommonsMultipartResolver,依赖Apache下的jakarta包
  2. StandardServletMultipartResolver, 依赖Servlet3.0+, 不需要第三方包 【推荐】

在Spring MVC容器配置文件中加入以下即可

<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>

然后在web.xml里面配置其初始化属性(在Spring MVC的dispatcer servlet中)

  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <!--临时文件的目录-->
            <location>/home/lin/</location>
            <!-- 上传文件最大2M -->
            <max-file-size>2097152</max-file-size>
            <!-- 上传文件整个请求不超过4M -->
            <max-request-size>4194304</max-request-size>
        </multipart-config>
    </servlet>

虽然web.xml文件会报错,提示not allow here / can not resolve,但是不影响使用。而且如果不配就无法使用。

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/83859469