简体   繁体   English

通过 JQuery AJAX 调用保存文件

[英]Save File through JQuery AJAX Call

I am using JQuery to send an AJAX request to a Node server (using Hapi).我正在使用 JQuery 将 AJAX 请求发送到节点服务器(使用 Hapi)。 The server responds with a PDF file correctly, but I am trying to save the file locally.服务器正确响应 PDF 文件,但我正在尝试将文件保存在本地。 The catch is that the PDF should only return if the POST sent the right data.问题是 PDF 只有在 POST 发送了正确的数据时才应该返回。 It's "protected" in other words and I don't want to just expose it publicly.换句话说,它是“受保护的”,我不想公开暴露它。

Frontend code:前端代码:

$.get('http://localhost:3000').done(function (data) {
  console.log(data);
});

Backend code:后端代码:

server.route({
  method: 'GET',
  path: '/',
  handler: async (request, h) => {
    return h.file('./static/sample.pdf', {
      mode: 'attachment',
      filename: 'sample.pdf'
    })
  }
});

I receive the data but nothing happens in the front-end UI.我收到数据,但前端 UI 中没有任何反应。 How can I download the PDF that is sent automatically?如何下载自动发送的PDF?

You can achieve that with html5 using您可以使用 html5 来实现这一点

<a href="http://link/to/file" download="FileName">Download it!</a>

Notice that this works only for same-origin URLs, or the blob: and data: schemes.请注意,这仅适用于同源 URL 或 blob: 和 data: 方案。 And this gets overridden by the Content-Disposition header from the server.这会被来自服务器的 Content-Disposition header 覆盖。

If you want to do this programatically you could do this如果您想以编程方式执行此操作,您可以执行此操作

    const element = document.createElement("a")
    element.setAttribute(
      "href",
      // you could also use base64 encoding here like data:application/pdf;base64,
      "data:text/plain;charset=utf-8," + encodeURIComponent('pdf binary content here') 
    )
    element.setAttribute("download", "file.pdf")

    element.style.display = "none"
    document.body.appendChild(element)

    element.click()

    document.body.removeChild(element)

Anyway this is only a useful method if u want to create/modify the downloaded data from the client side, but if u are getting it as it is from the server side then its better just to open a new url, letting the browser handle it.无论如何,如果您想从客户端创建/修改下载的数据,这只是一种有用的方法,但是如果您从服务器端获取它,那么最好打开一个新的 url,让浏览器处理它.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM