在SpringBoot的环境下,写上传文件的功能,结果没有获取到文件的问题(ServletFileUpload中getItemIterator(request)为空)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou_pp/article/details/85060076

在SpringBoot的环境下,写上传文件的功能,结果没有获取到文件的问题:

情况一:

使用Apache Commons FileUpload 组件上传文件时总是返回null,multipart/form-data类型文件的接收。

<!DOCTYPE html>    
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"    
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">    
    <head>    
        <title>Hello World!</title>    
    </head>    
    <body>    
       <form method="POST" enctype="multipart/form-data" action="/upload">     
           <p>文件1:<input type="text" name="id" /></p>    
           <!--
           <p>文件2:<input type="text" name="name" /></p>    
           <p>文件3:<input type="file" name="file" /></p>  
            -->  
           <p><input type="submit" value="上传" /></p>    
       </form>    
    </body>    
</html>     

情况二:

使用百度的插件webuplader,带css,js,swf文件,前端如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <link rel="stylesheet" type="text/css" href="/assets/dist/webuploader/webuploader.css">
    <script src="/assets/dist/webuploader/webuploader.js"></script>
    <script src="/js/Uploader.js"></script>
</head>
<div id="UploaderDialog" style="display: none;height: 592px">
    <div style="background-color: white; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;">
        <div id="uploader" class="wu-example">
            <!--用来存放文件信息-->
            <div id="fileList" class="uploader-list"></div>
            <div class="btns">
               <div id="picker" style="padding:0 8px 0 0">选择文件</div>
              <!--  <button id="picker" class="btn btn-default" style="width:75px;height:33px;margin:0 5px 5px 0">选择文件</button>-->
                <button id="ctlBtn" class="btn btn-default" style="width:75px;height:33px;margin:2px 0 5px 0">开始上传</button>
                <button id="cancleBtn" class="btn btn-default" style="width:75px;height:33px;margin:2px 0 5px 5px">取消上传</button>
            </div>
        </div>
    </div>
</div>
<body>
<script type="text/javascript">
    $(function() {
        $("#UploaderDialog").dialog({
            autoOpen : false, // 是否自动弹出窗口
            modal : true, // 设置为模态对话框
            resizable : true,
            width : 550, //弹出框宽度
            height : 205, //弹出框高度
            title : "上传文件" //弹出框标题
        });
        $("#back-button").click(function() {
            $("#UploaderDialog").dialog("close");
        });
    });
</script>
</body>
</html>

后台接收文件的处理方式都是一样的:

@RequestMapping("/uploadingfiles")
     public void uploadingfiles(HttpServletRequest request, HttpServletResponse response){
        DataSourceRouter.routerTo("222222");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String filename=null;
        String file_id = null;
        UPloadFile ups=new UPloadFile();
        try{
            ServletFileUpload upload = new ServletFileUpload();//文件上传解析器
            upload.setHeaderEncoding("utf-8");// 防止中文文件名乱码
            FileItemIterator iter = upload.getItemIterator(request);
            while(iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream input = null;
                System.out.println("121212121212121");
                try{
                    input=item.openStream();
                    if(!item.isFormField()){
                        if(input.available()>0) {
                            filename = item.getFieldName();
                            System.out.println(filename);
                            int xlh = phdyService.getMaxXlh();
                            ups = phdyService.uploadfiledj(xlh, input, filename);
                        }
                    }else{
                        if("id".equals(item.getFieldName())){
                            file_id = Streams.asString(input, "utf-8");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    IOUtil.close(input);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally{
            if(ups==null){
                ResponseResult rr = ResponseResult.defaultErr("上传失败");
                rr.write(response);
            }else{
                System.out.println(ups);
                System.out.println(ups.getFilename());
                System.out.println(ups.getWJscsj());
                System.out.println(ups.getWJscsj());
                //   ResponseBuilder builder=new ResponseBuilder();
                //  builder.writeJsonResponse(response,ups);
                ResponseResult.defaultOK(ups).write(response);
            }
        }



    }

其中FileItemIterator iter = upload.getItemIterator(request);这段获取的是空值。

问题的原因是:

spring-boot自带的org.springframework.web.multipart.MultipartFile
和Multipart产生冲突,如果同时使用了MultipartResolver 和ServletFileUpload,就会在iter.hasNext()返回false.然后整个循环就跳出去了。整个问题产生的原因是Spring框架先调用了MultipartResolver 来处理http multi-part的请求。这里http multipart的请求已经消耗掉。后面又交给ServletFileUpload ,那么ServletFileUpload 就获取不到相应的multi-part请求。因此将multipartResolve配置去除,问题就解决了。
 

在使用ServletFileUpload时需要关闭Spring Boot的默认配置 ,所以在配置文件中添加

spring.http.multipart.enabled=false 

猜你喜欢

转载自blog.csdn.net/zhou_pp/article/details/85060076