Ajax File Upload using Jquery in Struts2 : Many people face the problem of uploading the file using ajax jquery but in this blog, I will show you how to upload ajax file using jQuery in java.
Here I am using view page as a JSP and Controller as a struts2 you can use HTML or anything you want as a view page and Controller part you can use servlet or spring to Upload file using ajax jquery.
Below is my JSP page code I am using jQuery and JavaScript ajax file upload.
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"><script src='https://code.jquery.com/jquery-3.4.1.min.js'></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <script type="text/javascript"> function ajaxUploadFile() { if ($('#ajaxFile').get(0).files.length != 0) { var fd = new FormData(); var file = $('#ajaxFile')[0].files[0]; var filename = $('#ajaxFile').get(0).files[0].name; var checkExt = filename.split('.'); if (checkExt[1] == 'pdf' || checkExt[1] == 'docx') { fd.append('file', file); fd.append('fileName', filename); $.ajax({ url : 'ajaxFileUpload', type : "POST", enctype : 'multipart/form-data', data : fd, dataType : "JSON", contentType: false, processData : false, success : function(data) { //console.log(JSON.stringify(data)); console.log("Ajax file upload Message :"+data.fileUploadMsg); if (data.fileUploadMsg != "") { alert(data.fileUploadMsg); document.getElementById('ajaxFile').value = null; } else { alert(data.fileUploadMsg); document.getElementById('ajaxFile').value = null; } },error: function (jqXHR, textStatus, errorThrown) { if (jqXHR.status == 500) { console.log('Internal error: ' + jqXHR.responseText); } else { console.log('textStatus:'+textStatus); console.log('errorThrown: '+errorThrown); } } }); } else { alert("Upload Excel File Only") } } else { alert("Plz Upload a Excel File") } return false; } </script> </body> </html>Ajax file upload </head> <body>
NOTE: Here I am using Bootstrap 4 CSS and jQuery 3 as CDN you can use as per your requirement.
Ajax file upload JSP |
As I am using struts2 as a controller I need to map the action in struts.xml below is the code struts.xml.
Below is my controller code which I have been written in struts2 here I am using ajaxfileupload() method which takes File and Filename as input which I set from ajax call in JQuery.
package com.first.controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class AjaxCalled extends ActionSupport { private File file; private String fileName; private String fileUploadMsg; public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileUploadMsg() { return fileUploadMsg; } public void setFileUploadMsg(String fileUploadMsg) { this.fileUploadMsg = fileUploadMsg; } public String ajaxFileUpload() throws Exception { boolean isMultipart; try { HttpServletRequest request = ServletActionContext.getRequest(); isMultipart = ServletFileUpload.isMultipartContent(request); // if file in mandatory in ajax upload if not then remove isMultipart if (isMultipart) { if (file != null && file.length() != 0) { if (!fileName.isEmpty() && fileName.toUpperCase().endsWith(".PDF")) { System.out.println("FileName : " + fileName); System.out.println(" File : " + file); // Your File upload Code String message = fileUpload(file, fileName); // if file upload fail then error message System.out.println(" Message: " + message); if (message != null && message.trim().equals("")) { setFileUploadMsg("File Uploaded Successfully"); } else { setFileUploadMsg("Ajax file Upload Fail"); } } else { setFileUploadMsg("Ajax file Upload only pdf file uploaded"); } } else { setFileUploadMsg("Unable to Find Ajax file Upload"); } } else { setFileUploadMsg("Plz Uplaod Ajax file"); } } catch (Exception e) { e.printStackTrace(); setFileUploadMsg("Invalid Ajax file Upload"); } return ActionSupport.SUCCESS; } private String fileUpload(File file2, String fileName2) { // Your File upload Code return null; } }
Ajax file upload JSP |
ajax file upload struts2 |
While uploading a File all the necessary validation has been taken care in this ajax file upload Example so use directly in your code not to worry about the validations.
If you find any problem please do comment.