jQuery.ajax servlet返回一个文件

时间:2013-10-29 14:26:57

标签: java jquery ajax servlets

我对jQuery和ajax很新,我有一个问题。 在jsp我打电话

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);
            }
    });

然后在我做的servlet中

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();
    }
}

但是在ajax函数中,即使消息由文件内部的字符串组成,我也始终无法获得成功。我该怎么办?

2 个答案:

答案 0 :(得分:2)

删除dataType: "json",选项,您将看到一些调试信息。

顺便说一下,有一个满足你需要的jQuery选项:

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); })

取自这个答案:https://stackoverflow.com/a/9970672/1420186

修改

你的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);
          }
    });
}

在Servlet中,如果文件不存在,只需返回“FAIL”字符串,否则返回文件URL。

希望有所帮助。

答案 1 :(得分:1)

不要使用Ajax调用//使用隐藏表单方法

<form action='../servletname' method='POST' id='formid'>
                <input type='hidden' value='' name='name' id='id'/>
                <input type='hidden' value=' ' name='name'  id='id' />
            </form>

点击按钮提交表单

$('#formid').submit(); 

在servlet中

response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=filnemae.fileformat");

 ServletOutputStream out = res.getOutputStream();

写入ouput流然后关闭或刷新

如果您通过server.xml中的更新postize发送大数据