首页 > 解决方案 > 文件在 rails 中始终以 PDF 格式下载

问题描述

我在我的 rails 应用程序中定义了一个上传器。我在这里面临的问题是,当我下载上传的文件时,它会以 PDF 格式下载,而不是文件的实际格式。

class DocumentController < MyAccountController
  def show
   @agency = current_agency
   redirect_to @agency.document.url
  end
end

这是文件的网址。但该文件始终以 PDF 格式下载

"http://localhost:3000/uploads/agency/document/61/document.jpeg"

下载文件的方法。

<script>
 downloadDocument() {
   var url = 'myagency/document',
   fileName = "EngagementLetter",
   file;
   this.$axios.get(url, { responseType: 'blob' })
   .then(response => {
    file = new Blob(
    [response.data],
    { type: 'application/pdf, image/gif, image/jpeg' }
   );
   FileSaver.saveAs(file, fileName);
   });
  }
</script>

标签: ruby-on-railsvue.jscarrierwave

解决方案


我遇到了类似的问题,以下对我有用。

      var url = 'myagency/document',
      fileName = "EngagementLetter",

      axios.get(url, { responseType: 'blob' })
      .then(response => {
        console.log(response.data)
        const url = window.URL.createObjectURL(response.data)

        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName )
        document.body.appendChild(link)
        link.click()
        link.remove()
      });

您会注意到它response.dataBlob {size: ####, type: "image/jpeg"}控制台中。您不必指定类型。


推荐阅读