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";
}
  • 上传成功后的页面代码再也不赘述
相关文章
相关标签/搜索