使用ajax上传文件,未上传文件,报错400 (Bad Request)

js代码如下

var formData = new FormData();
            for (var i = 0; i < data.length; i++) {
                if(data[i]){
                    formData.append("datafiles", data[i]);
                }
            }
            formData.append("content", content);
            $.ajax({
                url: '${pageContext.request.contextPath}/forum/addContent',
                type: 'post',
                data: formData,
                cache: false,
                contentType:false,
                processData:false,
                success: function(result) {
                    console.log(res);
                }
            });

其中打印data中的数据都是undifine,datafiles也是undifine

这时候报错400 (Bad Request)

也就是说未进入服务器,后台代码如下:

@RequestMapping("/addContent")
    @ResponseBody
    public String uploadFile(Entrance_forum_content entrance_forum_content,@RequestParam(value="datafiles",required=false) CommonsMultipartFile[] files, HttpServletRequest request)throws Exception{
    if(files!=null){
        String filePath = request.getSession().getServletContext().getRealPath("/upload/entrance_forum");
        Map<String,String> map = new HashMap<String, String>();
        CommonsMultipartFile multipartFile = null;
        for (int i = 0; i < files.length; i++) {
            multipartFile = files[i];
            String uploadFile = SuperUploadFileUtil.uploadFile(multipartFile, filePath);
            if(uploadFile!=""){
                map.put("img"+(i+1), "/upload/entrance_forum/"+uploadFile);
            }
        }
        SuperBeanUtils.setFieldValue(entrance_forum_content, map);
    }
    return "success";
    }

重点在参数部分,之前我是未使用

required=false
,那么如果不上传文件,datafiles中都为undefined,后台默认为没有该参数,所以报错,所以加上
required=false
即可
上一篇:iview Upload组件多文件上传,以及vue文件下载


下一篇:php中图片文件上传,显示缩略图