Skip to content
Advertisement

Uploading a file with JavaScript/Ajax to SpringBoot endpoint

I am new to front-end development and am having troubles piecing together a solution for this specific form setup.

I have an already created jsp representing this instance creation page. It’s a form containing numerous drop downs and check boxes. I need to add a file upload option to it.

The jsp is set up like this…

JavaScript

Here’s my input field

JavaScript

Now I have an ajax call that I was originally wanting to use before I realized that the whole form is attempting to submit when I uploaded the file. Here it is…

JavaScript

I got this suggestion in researching how to upload a file with jQuery/ajax and Spring Boot (I am using Spring Boot to create my endpoint). Here are some articles that I have been reading in an attempt to understand how to do this…

https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/

http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-ajax-multipartfile-application-downloadupload-files-springboot-jquery-ajax-bootstrap#3_Implement_upload_controller

and many more. This seemed like the solution until I realized this was a form and I think I need to save all the fields at once. This is going to mean that I have to modify the already created ajax function that saves this form and passes it to the end point. Now I don’t know how to get my MulitpartFile in as part of this different function. The existing one is like this…

JavaScript

This is exactly where I am stuck and I need to be pointed in the correct and productive direction.

I don’t know if this will help but here’s my end point that looks like the one I have to hit with my file param added…

JavaScript

EDIT: I have done some curl troubleshooting and it’s the MulitpartFile that’s failing. I am passing it as suggested yet I am getting this exception:

JavaScript

Advertisement

Answer

You can try below code:

JavaScript

And in controller, you needn’t declare consumes = "application/json"

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement