How to send file via Ajax call to Servlet - java

I have an HTML form in AEM where I have to attach the files and the same files will be sent to one Rest API via Java Servlet.
I am calling the Java Servlet via Ajax and able to send other String data to Java Servlet but not able to send the file Array which contains the files attached to the HTML Form attachment option while submitting the Form. How can I get the file in Java servlet?
In JS
var myFile [] is what I am sending in a ajax call.
$.ajax({
url: /servletUrl,
type: 'post',
data: {
'myFile': myFile,
},
success: function(response){
}
});
In Java :
Enum paramObject = request.getparameter();
When I put the object in HashMap and try to get the file, its type is coming as String not Object.
I am not sure where I am setting it as String.

The servlet has to be able to process Multipart-Messages.
I do not know AEM, but in Jakarta / Java Enterprise Edition / JEE / J2EE:
you have to specifically add the #Multipart annotation to the servlet.
Now, open your browser, press F12 to go into debug details, and when you trigger the request, the Network tab will display alle the infos that are posted. Look up the name of the parameter, usually it's calles file[]
When handling the request in the servlet, you can use the HttpServletRequest's request.getParts() method to find all parameter parts.
With final Part filePart = request.getPart(pFileParamName); and final InputStream filecontent = filePart.getInputStream(); you will be able to access the data.
And this will probably be very similar in most servlet frameworks.

Related

invoke jsp from java code and get output

I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.
public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}
The output of the JSP is html.
Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:
void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}
I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?
Oups. The servlet specification requires the servlet container to be able to execute a JSP file. This is commonly done by converting the JSP to plain Java and the generating a servlet class file.
If you are outside of a servlet container you must:
* either fully implement a JSP execution environment, for example by using sources from a servlet container like Tomcat
* or rely on a servlet container to convert the JSP file to a .java or .class servlet and then use the Servlet interface methods on it
Alternatively, you could try to use a headless browser to capture the output of the application.

Its possible to POST a form with AJAX to java servlet and redirect?

I explain my problem:
I have one JSP webpage and I have one AJAX call that send some data to one servlet.
The servlet that receive the data have to send this data and more other information to an external URL. This external URL have to be load in the screen with the POST params sent.
Its possible to do this with AJAX and JAVA?
I know that the easy way is send a normal FORM from MYPAGE to this external website (without the servlet) and the form automatic redirects to this external URL, but I dont have all the data, so I need one intermediate servlet to get it...
The schema:
MYPAGE -- (AJAX request to one servlet)---> MY SERVLET ---(POST to an URL with params)---> EXTERNALWEBSITE
The user have to see in the screen the EXTERNALWEBSITE like if the call would be direct between MYPAGE and the EXTERNALWEBSITE
You could send the additional data that you need in the response of your Ajax call. Then on the client-side, right after your Ajax call, you can do a jQuery.post() to the external URL that will include all the data.

How to download a file using XMLHttpRequest

I am posting html content to the serverside and converting it to PDF and streaming the file back.
But am not able to download the file using:
var formData = new FormData();
formData.append("htmlContent", strHTML);
var request = new XMLHttpRequest();
request.open("POST", "RenderHtmlAsPDF.jsp");
request.send(formData);
Download works when I create a dynamic form and post the html content targeting it to an iframe. But I am limited by the amount of data I can send.
You can't download a file with AJAX. However you can "simulate" the behaviour by doing the folowing: make the ajax post request for file generation, after the file was generated on the server, generate a token or id with witch you can identify the file, send it back to the client and when you have received the response token on the client simply generate an iframe with the src pointing to a method on your back-end which receives the token and sends back the file.

Jersey servlet returns zip file that contains more bytes than response sent

I'm trying to implement a simple servlet that returns a zip file that is bundled inside the application (simple resource)
So I've implemented the following method in the server side:
#GET
#Path("{path}/{zipfile}")
#Produces("application/zip")
public Response getZipFile(
#PathParam("path") String pathFolder,
#PathParam("zipfile") String zipFile) IOException {
String fullPath= String.format("/WEB-INF/repository/%s/%s",
pathFolder, zipFile);
String realPath = ServletContextHolder.INSTANCE.getServletContext()
.getRealPath(fullPath);
File file = new File(realPath );
ResponseBuilder response = Response.ok((Object) file);
return response.build();
}
When I call this method from the borwser, the zip file is downloaded and its size is the same number of bytes as the original zip in the server.
However, when I call this using a simple XMLHttpRequest from my client side code:
var oXHR = new XMLHttpRequest();
var sUrl = "http://localhost:8080/path/file.zip"
oXHR.open('GET', sUrl);
oXHR.responseType = 'application/zip';
oXHR.send();
I can see in the Network tab of the Developer tools in chrome that the content size is bigger, and I'm unable to process this zip file (for instance JSzip doesn't recognize it).
It seems like somewhere between my response and the final response from org.glassfish.jersey.servlet.ServletContainer, some extra bytes are written/ some encoding is done on the file.
Can you please assist?
Best Regards,
Maxim
When you use an ajax request, the browser expects text (by default) and will try to decode it from UTF-8 (corrupting your data).
Try with oXHR.responseType = "arraybuffer"; : that way, the browser won't change the data and give you the raw content (which will be in oXHR.response).
This solution won't work in IE 6-9 : if you need to support it, check JSZip documentation : http://stuk.github.io/jszip/documentation/howto/read_zip.html
If it's not the right solution, try downloading directly the zip file (without any js code involved) to check if the issue comes from the js side or from the java side.

How to accept both multipart and application/x-www-form-urlencoded?

I built a servlet that allows uploading a file or alternatively uploading a list as input. So far I've handled it by setting the servlet to accept multipart/form-data so even if there is no file, I read the list as a part.
I'm now trying to call this servlet to upload a list through a JQuery AJAX method instead of through a form. If I try to upload a list normally through the method, I get:
org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8
If I set the contentType as multipart/form-data like so:
$.ajax({
url: someUrl,
type: 'POST',
contentType: 'multipart/form-data',
data: {list: inputList}
});
I get this error instead:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
My question is if there is some way to configure the servlet to accept both content types or alternatively is there some way to write the ajax data to upload multipart/form-data?
I know it's simple to upload multipart/form-data using the FormData API, but I need to support IE9 so this is not an option.
I suggest you to use Apache Commons FileUpload library. It provides you with a uniform interface, no matter which type of form was submitted, and makes it easy to work with uploaded files. See Section Processing the uploaded items of the User Guide, it should give you a general idea how it works.

Categories