springmvc实现多文件上传

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--指定文件的编码-->
    <property name="defaultEncoding" value="utf-8"></property>
    <!--指定上传文件的最大大小-->
    <property name="maxUploadSize" value="1024000"></property>

</bean>
  • 如果设置了文件的最大限制,则需要在配置文件中添加如下代码,来指定超出限制时所跳转的错误页面:
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
    <property name="exceptionMappings">  
        <props>  

            <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop>  
        </props>  
    </property>  
</bean>  
  • jsp页面中添加如下代码:
<%--
  Created by IntelliJ IDEA.
  User: elin
  Date: 15-7-4
  Time: 下午7:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form action="<%=request.getContextPath()%>/user/uploadHandle" method="post" enctype="multipart/form-data">
  描述:<input type="text" name="desc">
  上传文件:<input type="file" name="file" multiple="multiple">
  <input type="submit" value="上传">
</form>
</body>
</html>
  • 控制器类中加入如下代码:
@RequestMapping("/uploadHandle")
public String uploadHandle(@RequestParam("desc") String desc,@RequestParam("file") MultipartFile[] multipartFiles) throws Exception{
    //        遍历数组中的多个文件,示例jsp页面为只上传一个文件
    for (MultipartFile multipartFile : multipartFiles) {

        String path = "/home/elin/workspace/upload/";
//            获取原始图片名称
        String oldFileName = multipartFile.getOriginalFilename();
//            设置随机的图片名称
        String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));

//            创建新的文件
        File file = new File(path + newFileName);

//            把内存中的图片写入对应的目录
        multipartFile.transferTo(file);
    }
    return "success";
}
  • 上传成功后的页面代码不再赘述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值