SpringMVC上传文件为空,servletFileUpload.parseRequest解析为空的问题

在SpringMVC项目中,遇到文件上传为空的问题,经过调试发现上传的request对象为空。原因是由于Spring配置中特定的配置导致。移除该配置后,文件上传恢复正常。
摘要由CSDN通过智能技术生成

控制器中业务代码如下:

@RequestMapping(path = "/upload")
    public String testupload(HttpServletRequest request)throws Exception  {
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(path);
        File file=new File(path);
        if(!file.exists())
            file.mkdirs();
        DiskFileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);
        System.out.println(upload);
        //解析request 获取上传文件
        List<FileItem> fileItems = upload.parseRequest(request);
        System.out.println(fileItems);
        //判断是否是上传文件
        for (FileItem fileItem : fileItems) {
            if(fileItem.isFormField()){
                //isFormField()判断是否普通表单类型
            }else {
                String name = fileItem.getName();
                fileItem.write(new File(path,name));
            }
        }
        return "success";
    }

开始以为是文件路径的问题
在项目里面一直找不到生成的路径
后来根据调试发现默认是上传到了tomcat下的webapp中
但是文件一直是空
发现问题原因:
解析出的request对象一直是空的
解决方法:
去掉在spring配置中的这段配置:

<!-- 文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="DefaultEncoding" value="UTF-8" />
        <property name="MaxUploadSize" value="1048576" />
        <property name="MaxInMemorySize" value="4096"/>
    </bean>

然后发现文件就可以正常上传了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值