当前请求不是多部分请求

时间:2016-07-10 16:55:41

标签: java spring-mvc file-upload spring-boot

在通过ajax上传我的文件时,我面临的是Exeption

  

org.springframework.web.multipart.MultipartException:当前请求不是多部分请求

我谷歌这个并找到许多解决方案,应用所有这些解决我的问题没人 -

以下是我的html-file

<form id="upload-file-form">
   <label for="upload-file-input">Upload your file:</label>
   <input id="upload-file-input" type="file" name="uploadfile" accept="*" enctype="multipart/form-data" />
</form>

ajax的脚本 -

$.ajax({
         url: "/util/uploadFile",
         type: "POST",
         data: {'uploadfile':new FormData($("#upload-file-form")[0])},
         enctype: 'multipart/form-data',
         processData: false,
         contentType: false,
         cache: false,
         success: function () {},
         error: function () {}
         });

这是我的Spring启动控制器(&#34; / util&#34;) -

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile) {
        System.out.println("----------------");
        System.out.println("----------------" + uploadfile);
        return "success";
    }


    @Bean
    public MultipartConfigElement multipartConfigElement() {
        return new MultipartConfigElement("");
    }

    @Bean
    public MultipartResolver multipartResolver() {
        org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(4000000);
        return multipartResolver;
    }

1 个答案:

答案 0 :(得分:1)

您正在发送导致问题的Ajax请求和you are using name of input field directly in your controller。因为当ajax请求到达controller it doesn't found any parameter with name "uploadfile"时,这才为您带来错误。

在这里,我只是放置文件的密钥,它接受请求。下面编写的代码对我有用。

Ajax代码

var formData = new FormData();
var file = $('#fileInputId')[0].files[0];

formData.append("myFileKey", file);

$.ajax({
        url : 'myUrl',
        type : 'POST',
        data : formData,
        enctype : 'multipart/form-data',
        contentType : false,
        cache : false,
        processData : false,
        success : function(response) {},
        error: function(){}    
     )};

Java控制器代码:

    @PostMapping(value = { "/myUrl" }, consumes = { "multipart/form-data" })
    public ModelAndView readFileData(@RequestParam("myFileKey") MultipartFile uploadedFile) throws IOException 
   {
                 Your Stuff...... 
   }