使用Spring CommonsMultipartResolver 上传文件

可以在controller(spring mvc)  或者 action (struts mvc)
中直接使用CommonsMultipartResolver

 

private String upload(HttpServletRequest request){
    String path = "";
    String pathSum = "";
    CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    if (commonsMultipartResolver.isMultipart(request)){
        MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest)request;
        Iterator iter = multipartRequest.getFileNames();// 格式大概是{files=[文件对象,文件对象]}
        while (iter.hasNext()) {
            List<MultipartFile> listFile = multipartRequest.getFiles(iter.next().toString());// 如果是多个input,则靠iter遍历,若一个input选择了多个文件,则靠这个listfile去遍历
            for (int i = 0; i < listFile.size(); i++) {
                String fileName = Utils.getuuid() + listFile.get(i).getOriginalFilename().substring(listFile.get(i).getOriginalFilename().lastIndexOf("."));
                path = context.getRealPath("/upload") + "/" + fileName;
                pathSum += (path + ",");
                File f=new File(path);
                try {
                    listFile.get(i).transferTo(f);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        pathSum = pathSum.substring(0,pathSum.length()-1);// 去掉最后一个逗号
    }
    return pathSum;
}

 

可以在spring配置文件中配置

<!-- 支持上传文件 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="419430400"/> 

<property name="defaultEncoding" value="UTF-8"/>

</bean>


 

jsp code


<form id=”fileUploadForm” method=”post” action=”XXX.do?method=fileUpload” enctype=”multipart/form-data”>
<tr>
<td>File:</td>
<td><input type=”file” name=”file” multiple="multiple"></td>

</tr>
<tr>
<td><input type=”hidden” name=”fileOwner” value=”1002″/></td>
<td><input type=”submit” value=”submit”></td>
</tr>
</form>

 

发布者:songJian   点击数:1263   发布时间:2017-06-27 21:39:07   更新时间:2017-12-14 13:00:45
正在加载评论...
相关文章