【问题标题】:jQuery.ajax servlet return a file [duplicate]jQuery.ajax servlet返回一个文件[重复]
【发布时间】:2013-10-29 14:26:57
【问题描述】:

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

【问题讨论】:

    标签: java jquery ajax servlets


    【解决方案1】:

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

    希望对您有所帮助。

    【讨论】:

    • 我看到了那个答案,问题是在servlet中我会使用documentId(尚未实现)通过一些查询来搜索文件的名称,所以我不能直接询问下载。
    • @ReTanica 这应该不是问题。虽然如果你只是想下载文件,你根本无法使用 AJAX,而只需使用window.location.href = url
    • @ReTanica 您可以先发送一个 ajax 请求以确认文件存在,然后使用$.fileDownload 下载它,或者按照@Anthony Grist 的建议使用window.location.href = url
    • 我也有同样的想法。但是我的老板在 jquery 1.4 中强迫我这样做。我很生气,因为我没有看到任何可能的解决方案。无论如何,我怎样才能调用 servlet 并接收文件下载,或者如果找不到文件则会出错?
    • @ReTanica 我已经更新了我的答案。
    【解决方案2】:

    不要使用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(); 
    

    在小服务程序中

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

    写入输出流然后关闭或刷新

    如果您通过 server.xml 中的 post update postsize 发送大数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 2016-07-31
      • 2021-01-27
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      相关资源
      最近更新 更多