Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass file object through ajax sumbit with spring mvc controller

I am trying to pass the file object through jquery ajax submit.
JSP code

<div id="import-file">
        <input type="file" id="file"/>
        <table>
        <tr><td><input type="radio" name="type" value="csv"></td><td>CSV File</td></tr>
        <tr><td><input type="radio" name="type" value="excel"></td><td>Excel spread sheet</td></tr>
        <tr><td><input type="radio" name="type" value="tab"></td><td>Tab delimited</td></tr>
        </table>
</div>

Java script code

        var type = $($('input:radio:checked')[0]).val();
        var file = $("#file")[0].files[0];
        alert($("#file")[0].files[0].name);
        $.ajax({
            data :{
                "file" : file,
                "type" : type
            },
            type: "POST",
            url: "fileupload.htm",
            success: function(data){
                alert(data);
            },
            error:function(err){
                alert(err);
            }
        });

finally here is my spring controller code:

@RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
    public @ResponseBody String uploadFile(@RequestParam String type, @RequestParam("file") MultipartFile file){
        logger.info("file type : "+type + "file is "+file.toString());
        return "SUCCESS";
    }

Am getting NS_NOINTERFACE: Component does not have requested interface [nsIDOMBlob.slice] error in my firebug console.

like image 269
Ramesh Kotha Avatar asked Jan 12 '23 17:01

Ramesh Kotha


1 Answers

I have solved it like this:

JavaScript code

var formData = new FormData($('form')[0]);    
    console.log("form data "+formData);
    $.ajax({
        url: 'fileupload.htm',
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            alert(data);
        },
        error: function(err){
            alert(err);
        }
    });

JSP Code

<form action="fileupload.htm" method="post" enctype="multipart/form-data" name="fileinfo">
<input type="file" name="fileName" id="file"/>
</form>

Spring Controller:

@RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
    public @ResponseBody String uploadFile(@RequestParam("fileName") MultipartFile file){
        try{
            logger.info("file is "+file.toString());

        }catch(Exception e){
            return "error occured "+e.getMessage();
        }
    }

Hope it helps some body.

like image 144
Ramesh Kotha Avatar answered Jan 31 '23 08:01

Ramesh Kotha