java - jQuery.ajax servlet 返回一个文件

标签 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函数中,我从来没有成功过,我总是收到错误消息,即使该消息是由文件内的字符串组成的。我能做什么?

最佳答案

删除 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。

希望有帮助。

关于java - jQuery.ajax servlet 返回一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661011/

相关文章:

javascript - all 选择器 ("*") 在 jQuery 中如何工作?

javascript - 为什么我的表格没有部分呈现?

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 如何在 Hibernate 中将子类映射到父类?

java - 从 PL/SQL 中的数据创建 "on the fly"图形图像

jquery - 使用 jQuery 交换 2 个 div 的位置和 Z-Index

jquery - 使用 jQuery 从 html 中删除元素

java - 使用 JSP 中的浏览按钮选择文件夹

php - 使用 Jquery 和 Ajax 来自服务器的响应

javascript - 如何使用 PHP/JS 计算下拉菜单的值?