I try to send multiple input data from a HTML-Form in a JSP to a Java-Servlet via an AJAX-Request. In my case: a select option, one radio button and a file (A PDF or XML, in the example code below it should always be a PDF).
The idea is, that I can process the user data on the servlet, while the user can stay on the page and gets informed after that. The problem I have is, that I can catch the data from the select tag and the radio button but not the uploaded file.
How can I send different data to a servlet while the user stays on the same page and receives the response? What do I have to change to receive it on the server in the servlet and later return it as a response?
The example output in the servlet looks something like this:
Hit POST Method!
myOptions=optionOne&myInput=PDF!
Form from the JSP:
<form id="myUploadForm" action="processMyUpload" method="post" enctype="multipart/form-data">
<div>
<select name="myOptions">
<option value="optionOne">Option 1</option>
<option value="optionTwo">Option 2</option>
</select>
</div>
<div>
<input name="myInput" value="PDF" type="radio">PDF<br>
<input name="myInput" value="XML" type="radio">XML<br>
</div>
<input class="myUploadedFile" name="file" id="file" type="file" accept="application/pdf">
<input class="myUploadButton" id="myUploadButton" value="Upload" type="submit">
</form>
The AJAX Request in the same JSP: (From the User BalusC How to use Servlets and Ajax?)
$(document).on("submit", "#myUploadForm", function (event) {
var $form = $(this);
console.log("FORM: " + JSON.stringify($form));
$.post($form.attr("action"), $form.serialize(), function (response) {
console.log("POST response" + JSON.stringify(response));
});
event.preventDefault();
});
The Java-Servlet:
@WebServlet(urlPatterns = {"/processMyUpload"})
@MultipartConfig
public class processMyUpload extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hit POST Method!");
BufferedReader br = request.getReader();
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}