javaajaxspring-mvcenctype

Can't Pass MultipartFile through Ajax JAVA


I'm trying to send a file from my jsp to controller via ajax, im getting EXCEPTION:Null Error, below is my code:

Controller:

@RequestMapping(value = "/schedulebatch",method = 
RequestMethod.POST,params="insertData")
public @ResponseBody String addBatch(@RequestParam(
@RequestParam(value="upfile",required=false) MultipartFile upfile) throws 
Exception {  if(!upfile.isEmpty()){
                    System.out.println("test1");}

View:

 $("#submit-btn").click(function(){
	
	
	var upfile = document.getElementById('upfile').enctypeVIEW;
    alert('test');
	if(batchname==null || fromdate == null || partners == null || interval == 
    null){
		$('#insertmodalalert').empty();
    	$('#insertmodalalert').append('<div class="alert alert-info"><strong 
    >NOTICE |</strong> Please fill out the required form. </div>');
    	$('#alertMod').modal();
    	$('#okbtn').click(function(){
    		window.location.reload(true);
    	});
	}
	else{
		
		$.ajax({
			
			type: "POST",
			url: "schedulebatch?insertData",
			data: {"upfile" : upfile},

			        
			        success: function(response){
						// alert('test');
			        	$('#insertmodalalert').empty();
			        	$('#insertmodalalert').append('<div class="alert alert- 
   info"><strong >NOTICE |</strong> '+response+' </div>');
			        	$('#alertMod').modal();
			        	$('#okbtn').click(function(){
			        		$('#alertMod').modal('hide');
			        		window.location.reload(true);
			        	});
			        },           
			        error: function(xhr, status, error) {
			        	  
			        	  var err = eval("(" + xhr.responseText + ")");
			        	// alert('test');
			        	  // Display the specific error raised by the server 
    (e.g. not a
			        	  //   valid value for Int32, or attempted to divide by 
    zero).
			        	  $('#insertmodalalert').append('<div class="alert 
    alert-danger"><strong >NOTICE |</strong> '+err.Message+'</div>');
			        		$('#activateMod').modal();
			        		
			        		$('#okbtn').click(function(){
				        		$('#alertMod').modal('hide');
				        		window.location.reload(true);
				        	});
			        }     
			    });
		//alert("Test");
	}

HTML:

 File to upload: <input class="form-control" type="file" name="upfile" 
    accept=".csv" id="upfile">
<button type="submit" class="btn btn-success" id="submit- 
   btn">Submit</button>

I narrowed down the code to the only thing that gives me error, thanks in advance. It gets the Multipart file successfully but im not sure why it gives a null exception error


Solution

  • When I uploading files with my RestController in Spring Boot I used like below and everything is fine :

    @PostMapping
    public ResponseEntity<User> post(UserCreateRequest request, @RequestPart("file") MultipartFile file) throws IOException {
        ftpService.uploadPhoto(file.getOriginalFilename(), file.getInputStream());
    
         return ResponseEntity.ok(userService.create(request));
     }
    

    So may be you can try to change your code as below:

    @RequestMapping(value = "/schedulebatch",method = 
    RequestMethod.POST,params="insertData")
    public @ResponseBody String addBatch(@RequestPart("upfile") MultipartFile upfile) throws Exception {  
        if(!upfile.isEmpty()){
            System.out.println("test1");
        }
    }
    

    And your content-type should be multipart/form-data so I added an example html&ajax form request:

    <html>
    
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
            <script>
                $(document).ready(function () {
    
                    $('#btnSubmit').click( function(e) {
                        e.preventDefault();
    
                        var form = $('#my-form')[0];
                        var data = new FormData(form);
    
                        $.ajax({
                            type: "POST",
                            enctype: 'multipart/form-data',
                            url: "http://localhost:8080/schedulebatch",
                            data: data,
                            processData: false,
                            contentType: false,
                            cache: false,
                            timeout: 600000,
                            success: function (data) {
                                alert("success")
                            },
                            error: function (e) {
                                alert("ERROR : ", e);
                            }
                        });
                    });
                });
    
            </script>
    
        </head>
    
        <body>
    
            <form method="POST" enctype="multipart/form-data" id="my-form">
                <input type="file" name="upfile"/><br/><br/>
                <input type="submit" value="Submit" id="btnSubmit"/>
    
            </form>
    
        </body>
    
    </html>