Vue + Laravel:如何正确下载PDF文件?

Fra*_*ssi 7 javascript php pdf laravel vue.js

情况:

前端:Vue.后端:Laravel.

在Web应用程序内部,我需要让用户下载某些pdf文件:

  • 我需要Laravel获取该文件并将其作为API GET请求的响应返回.
  • 然后在我的Vue Web应用程序中,我需要获取文件并下载它.

代码:

API:

$file = public_path() . "/path/test.pdf";

$headers = [
    'Content-Type' => 'application/pdf',
];
return response()->download($file, 'test.pdf', $headers);
Run Code Online (Sandbox Code Playgroud)

网络应用:

downloadFile() {
  this.$http.get(this.apiPath + '/download_pdf')
    .then(response => {
      let blob = new Blob([response.data], { type: 'application/pdf' })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'test.pdf'
      link.click()
    })
}
Run Code Online (Sandbox Code Playgroud)

结果:

使用此代码,我设法下载pdf文件.问题是pdf是空白的.

不知怎的,数据被破坏了(不是这个特殊的pdf文件的问题,我尝试了几个pdf文件 - 相同的结果)

来自服务器的响应:

来自服务器的响应本身很好:

在此输入图像描述

PDF:

问题可能出在pdf文件中.它肯定看起来已损坏的数据.这是它看起来如下的摘录response.data:

在此输入图像描述

问题:

如何使用Laravel为Web应用程序正确下载pdf文件和Vue?

谢谢!

Fra*_*ssi 16

解:

适当的归功于@Sagar指出我正确的方向.

上面的代码是正确的.缺少的是添加适当responseTypearraybuffer.

我被反应中的人吓到了????,这误导了我.这些问号是正常的,因为pdf是一个二进制数据,并且应由适当的读者阅读.

ARRAYBUFFER:

而arraybuffer正好用于保存二进制数据.

这是mozilla网站的定义:

ArrayBuffer对象用于表示通用的固定长度原始二进制数据缓冲区.你不能直接操纵ArrayBuffer的内容; 相反,您创建一个类型化数组对象或一个DataView对象,它表示特定格式的缓冲区,并使用它来读取和写入缓冲区的内容.

ResponseType字符串表示响应的类型.通过告诉它的arraybuffer,它会相应地处理数据.

只需添加responseType,我就可以正确下载pdf文件.

代码:

这是更正的Vue代码(与之前完全相同,但添加了responseType):

downloadFile() {
  this.$http.get(this.appApiPath + '/testpdf', {responseType: 'arraybuffer'})
    .then(response => {
      let blob = new Blob([response.data], { type: 'application/pdf' })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'test.pdf'
      link.click()
    })
}
Run Code Online (Sandbox Code Playgroud)

编辑:

这是一个更完整的解决方案,考虑到其他浏览器的行为:

downloadContract(booking) {
  this.$http.get(this.appApiPath + '/download_contract/' + booking.id, {responseType: 'arraybuffer'})
    .then(response => {
      this.downloadFile(response, 'customFilename')
    }, response => {
      console.warn('error from download_contract')
      console.log(response)
      // Manage errors
      }
    })
},

downloadFile(response, filename) {
  // It is necessary to create a new blob object with mime-type explicitly set
  // otherwise only Chrome works like it should
  var newBlob = new Blob([response.body], {type: 'application/pdf'})

  // IE doesn't allow using a blob object directly as link href
  // instead it is necessary to use msSaveOrOpenBlob
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(newBlob)
    return
  }

  // For other browsers:
  // Create a link pointing to the ObjectURL containing the blob.
  const data = window.URL.createObjectURL(newBlob)
  var link = document.createElement('a')
  link.href = data
  link.download = filename + '.pdf'
  link.click()
  setTimeout(function () {
    // For Firefox it is necessary to delay revoking the ObjectURL
    window.URL.revokeObjectURL(data)
  }, 100)
},
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢@FrancescoMussi!这非常有帮助。我的 pdf 下载但无法打开或打开时出现无法打开的错误。当我添加responseType时,一切正常! (2认同)

Sag*_*uja 5

您将无法进行下载Laravel,Vue因为两者都在我假设的不同端口上运行.

即使你尝试这样的事情.

public function getDownload()
    {
        //PDF file is stored under project/public/download/info.pdf
        $file= public_path(). "/download/info.pdf";

        $headers = [
              'Content-Type' => 'application/pdf',
           ];

    return response()->download($file, 'filename.pdf', $headers);
    }
Run Code Online (Sandbox Code Playgroud)

当您Laravel使用Vue js库向端口尝试发送标头并尝试在库中发送该pdf内容时,它将无济于事

试试这个 从这里获得帮助