2

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
  • 544
  • 2
  • 9
  • 17

2 Answers2

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.

Community
  • 1
  • 1
Tony Dinh
  • 6,668
  • 5
  • 39
  • 58
  • I 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 . – MarkWarriors Oct 29 '13 at 14:33
  • @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. – Anthony Grist Oct 29 '13 at 14:34
  • 1
    @ReTanica You can send an ajax request first to confirm that the file is exists, then use `$.fileDownload` to download it or just `window.location.href = url` as @Anthony Grist suggested. – Tony Dinh Oct 29 '13 at 14:37
  • I 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? – MarkWarriors Oct 29 '13 at 14:39
  • Unfortunally 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! – MarkWarriors Oct 29 '13 at 14:55
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

abhinavsinghvirsen
  • 1,853
  • 16
  • 25