javascript - 请求通过ajax下载servlet文件(请不要使用jquery..)

标签 javascript ajax jsp servlets

流程是这样的:

  1. 从网络(jsp)上传一些pdf文件(通过ajax提交)
  2. 在后端我合并这些pdf
  3. 我通过ajax得到响应(合并的pdf)-->开始文件下载...

我在第三步中遇到问题。

我仅包含了提交要上传的文件(发布请求)并开始下载的相关代码。 我还放置了一个直接链接,它在 get 方法中调用相同的步骤并且有效。

我的问题出在哪里? 提前致谢...

这是jsp主体标签

<a href="/TestAjaxServletDownload/DownloadServlet" >
    download
</a>

<p><input id="sampleFile5" name="sampleFile5" type="file" /></p>

<p><input id="uploadBtn" type="button" value="Upload" onClick="javascript:performAjaxSubmit();"></input></p>

这是我的 javascript 标签内容

function performAjaxSubmit() {

        var sampleFile1 = document.getElementById("sampleFile5").files[0];
        var formdata = new FormData();

        formdata.append("sampleFile", sampleFile1);

        var xhr = new XMLHttpRequest();       

        xhr.onload = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
//              alert("ok..." + xhr.responseText);
                //?????????????????????????????
                document.location=xhr.responseText;               
            }
        };   

        xhr.open("POST","/TestAjaxServletDownload/DownloadServlet", true);
        xhr.send(formdata);

    }

这是我的 web.xml serverlet 映射标签

<servlet>
    <description></description>
    <display-name>DownloadServlet</display-name>
    <servlet-name>DownloadServlet</servlet-name>
    <servlet-class>test.DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownloadServlet</servlet-name>
    <url-pattern>/DownloadServlet</url-pattern>
  </servlet-mapping>

这是我的 servlet 代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("DO GET SERVLET MERGE");
        execute (request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("DO POST SERVLET MERGE");
        execute (request, response);
    }


    protected void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        File downloadFile = new File("c:\\data\\example.pdf");
        System.out.println("++++" + downloadFile.getAbsolutePath());
//      System.out.println(uploadPathTemp+mergeFileName);
        FileInputStream inStream = new FileInputStream(downloadFile);
         // obtains ServletContext
         ServletContext context = getServletContext();

         // gets MIME type of the file
         String mimeType = context.getMimeType(downloadFile.getCanonicalPath());
         if (mimeType == null) {        
             // set to binary type if MIME mapping not found
             mimeType = "application/octet-stream";
         }

         // modifies response
         response.setContentType(mimeType);
         response.setContentLength((int) downloadFile.length());

         // forces download
         String headerKey = "Content-Disposition";
         String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
         System.out.println(downloadFile.getName());
         response.setHeader(headerKey, headerValue);

         // obtains response's output stream
         OutputStream outStream = response.getOutputStream();

         byte[] buffer = new byte[4096];
         int bytesRead = -1;

         while ((bytesRead = inStream.read(buffer)) != -1) {
             outStream.write(buffer, 0, bytesRead);
         }

         inStream.close();
         outStream.close();

    }

最佳答案

改变怎么样

<a href="/TestAjaxServletDownload/DownloadServlet" > download </a>

<a id="pdfLink" href="/TestAjaxServletDownload/DownloadServlet" > download </a>

然后使用 document.getElementById('pdfLink').click()

关于javascript - 请求通过ajax下载servlet文件(请不要使用jquery..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556843/

相关文章:

java - 使用 c 时如何将 cookie 传递给资源 :import?

javascript - 尝试确定 select 是否选择了值时出现语法错误

ruby-on-rails - 在 Rails 3 中使用 Ajax 更新部分内容

javascript - 如何在不单击按钮的情况下打开 Bootstrap 模式?

javascript - 将数据从 javascript ajax 函数发送到 jsp

javascript - 页面自动滚动到 HTML 的特定元素

java - 通过 curl 使用 JSTL formatNumber 的浮点舍入错误

javascript - 如何在 Jasmine 测试框架中处理谷歌地图事件

javascript - 带有 .p12 和 pem 证书的 Node.js POST 请求输出 "Error: read ECONNRESET"

javascript - Mongo 中存储的数组无法与具有相同长度和值的 native JavaScript 数组进行深度断言比较