springMVC上传文件,MultipartHttpServletRequest、MultipartFile进行文件上传

本文介绍了如何在SpringMVC中使用MultipartHttpServletRequest和MultipartFile进行文件上传。首先,借助apache的common-fileupload和common-io库,创建上传文件的帮助类,并实现根据文件后缀进行类型判断。接着,配置springmvc-mvc.xml,启用CommonsMultipartResolver解析器。然后,编写文件上传控制器,提供返回List集合的方法以支持单个和多个文件上传。最后,展示了两种上传方式:传统的form表单和AJAX异步上传,并给出了运行效果截图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里使用apache的开源jar包完成上传功能,使用jar包分别是:common-fileupload.jar和common-io.jar 


先编写上传文件帮助类,如果需要区分文件类型,可以将文件后缀截取进行判断;

springmvc-mvc.xml配置,这里主要配置springmvc解析器CommonsMultipartResolver等等,这里主要是配置文件上传解析器,下面是配置文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc   
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.cw.cashier.controller.*" />

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 使用注解 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 不处理静态资源 -->
    <mvc:default-servlet-handler />

    <!-- 上传文件时需要用到的分解层,默认将编码转为urf-8,设置最大上传容量 ,最大内存-->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="102400000" />
        <prop
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值