简体   繁体   中英

File upload using ajax and spring

I am trying to upload a file and read it at the server side. But i am not able to read the file instead i am getting an exception

Required MultipartFile parameter 'file' is not present

Below is the code snippet for the same. Can you kindly tell me if i am doing something wrong here. Is there any other way to read the file sent by an ajax request at the server end.

<form  id="dealform" method="post" enctype="multipart/form-data" type="file">
<input type="file" name="file" id="upload_file" style="visibility: hidden;width:0px;height:0px;"/><input id="fg-upload-button" type="submit" value="Upload" style="display:none;"/>
</form>

this.getRecord              = function(params)      {

            var file = $('#upload_file').prop("files")[0];

            $.ajax({
                url         : /Upload,
                data        : file,
                type        : 'POST',
                dataType    : 'json',
                timeout     : json_timeout,
                error       : function(){
                    that.notifyGetDataError('error getting:');                  
                },
                success     : function(data){
                    that.notifyGetDataSuccess();
                }
            });
        };

In the controller :

@RequestMapping(value = "/Upload.json", method = RequestMethod.POST)
    public ModelAndView getContents(@RequestParam("file") MultipartFile file) { 
}

Using the below in applicationContext.xml

<bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

The code is passing the file itself as the payload to your server. However your controller is expecting the file to be send as a value of parameter "file"

You are sending your file as dataType="json" which may be causing you problem because your content-type is multipart/form-data

Follow this link FormData for ajax file upload

Another link for your problem is here

You can follow this link which has controller code for MultipartFile

 data        : {file1:file}

并在控制器中

getContents(@RequestParam("file1") MultipartFile file)

In controller method, just change the name of the request parameter to data:

@RequestMapping(value = "/Upload.json", method = RequestMethod.POST)
    public ModelAndView getContents(@RequestParam("data") MultipartFile file) { 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM