jQuery.ajax servlet return a file
Solution 1
dont use Ajax call use //use hidden form approach
<form action='../servletname' method='POST' id='formid'>
<input type='hidden' value='' name='name' id='id'/>
<input type='hidden' value=' ' name='name' id='id' />
</form>
on click of button submit form
$('#formid').submit();
in servlet
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=filnemae.fileformat");
ServletOutputStream out = res.getOutputStream();
write on ouput stream then close or flush
if you are sending large data through post update postsize in server.xml
Solution 2
Remove your dataType: "json",
options and you will see some debug informations.
By the way, there is a jQuery option that meet you need:
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); })
Taken from this answer: https://stackoverflow.com/a/9970672/1420186
EDIT:
Your JSP
function downloadDocument(documentId){
var action = "attachment.do";
var method = "downloadDocument";
var url = action + "?actionType="+method+"&documentId=" + documentId;
$.ajax({
url: url,
dataType: "text", // Change dataType to "text"
type: 'POST',
success: function(data){
if (data == "FAIL") {
alert("File not found!");
} else {
window.location.href = data; // Download the file
}
},
error: function (request, status, error) {
alert("The request failed: " + request.responseText);
}
});
}
In your Servlet, if the file is not exists, just return a "FAIL" string, else return the file URL.
Hope that helps.
Comments
-
MarkWarriors over 1 year
I'm pretty new to jQuery and ajax and i have a question. In a jsp I call
function downloadDocument(documentId){ var action = "attachment.do"; var method = "downloadDocument"; var url = action + "?actionType="+method+"&documentId=" + documentId; $.ajax({ url: url, dataType: "json", type: 'POST', success: function(data){ alert("downloaded!"); }, error: function (request, status, error) { alert(request.responseText); } });
then in the servlet I do
public void downloadDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException{ AttachmentActionForm form = (AttachmentActionForm)actionForm; ServletOutputStream out = response.getOutputStream(); try{ // Get the downloadFileName, the name of the file when it will be downloaded by user String downloadFileName = "hello.txt"; String mimetype = "application/x-download" // Get the byte stream of the file FileInputStream in = new FileInputStream(Global.ATTACHMENTS_SHARED_FOLDER_PATH + downloadFileName); // Print out the byte stream byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } response.addHeader("Content-Disposition", "attachment; filename="+downloadFileName); response.setHeader("Content-Length", Integer.toString(length)); response.setContentType(mimetype); in.close(); } catch(Exception e){ response.setContentType("text/text;charset=utf-8"); response.setHeader("cache-control", "no-cache"); System.out.println(e.getMessage()); out.println(e.getMessage()); }finally{ out.flush(); } }
But in the ajax function, I never get a success, all the time I get the error message, even if the message is composed by the string inside of the file. What can I do?
-
MarkWarriors over 10 yearsI saw that answer, the problem is that in the servlet I will search the name of the file with some query using the documentId (not implemented yet), so i can't directly ask the download .
-
Anthony Grist over 10 years@ReTanica That shouldn't be an issue. Though if you just want to download the file you could not use AJAX at all, and just do
window.location.href = url
instead. -
Tony Dinh over 10 years@ReTanica You can send an ajax request first to confirm that the file is exists, then use
$.fileDownload
to download it or justwindow.location.href = url
as @Anthony Grist suggested. -
MarkWarriors over 10 yearsI am of the same idea. But my boss is forcing me do that, in jquery 1.4. I'm just angry because I don't see any possible solution. Anyway, how can I call a servlet and recive the file download, or an error if the file is not found?
-
Tony Dinh over 10 years@ReTanica I have updated my answer.
-
MarkWarriors over 10 yearsUnfortunally is a file on an internal server, so I get the file and write it with the OutputStream, so I can't give them an url where download. But was a nice try!