【问题标题】:Rails API / react / axios downloads corrupted fileRails API / react / axios 下载损坏的文件
【发布时间】:2020-07-13 10:52:39
【问题描述】:

首先我用 WickedPDF 创建了一个 pdf。

pdf_string = WickedPdf.new.pdf_from_string(
  ActionController::Base.new.render_to_string(template: 'v1/invoices/invoice_template', filename: 'test.pdf')
)

invoice.attachment.attach(
  io: StringIO.new(pdf_string),
  filename: 'test.pdf',
  content_type: 'application/pdf'
)

我的应用程序设置为将文件存储在 prod 的 s3 和本地的 dev 中。为了测试,我还在 dev 中使用了 s3 来验证我的 pdf 是否正确生成并保存。因此,在它生成之后,我可以登录到 aws 并下载我的发票。一切都显示得很好。

现在我遇到的问题是尝试下载我的发票。当我下载它时,我的 pdf 是空白的。

我有一个如下所示的下载方法:

    response.headers['Content-Type'] = @invoice.attachment.content_type
    response.headers['Content-Disposition'] = "inline; #{@invoice.attachment.filename}"

    response.headers['filename'] = @invoice.filename

    @invoice.attachment.download do |chunk|
      response.stream.write(chunk)
    end

我也试过

    send_data @invoice.attachment.download, filename: @invoice.filename

而我的前端(react)使用 axios 来下载它:

  const downloadInvoice = (id) => {
    axios.get(`/v1/invoices/${id}/download`)
      .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', response.headers.filename);
          document.body.appendChild(link);
          link.click();
      })
      .catch(() => {});
  };

我有点困惑为什么我下载的 pdf 是空白的。如果我在我的存储文件夹中打开它,它会显示得很好。我的下载方式似乎有问题。

如果我为 S3 创建一个预签名 URL,则可行:

s3 = Aws::S3::Resource.new(client: aws_client)
bucket = s3.bucket('bucket-name')
obj = bucket.object("@invoice.attachment.attachment.blob.key)

url = obj.presigned_url(:get)

我可以将该 url 发送回前端并在新选项卡中打开它以查看 pdf。但这不是我想要的……

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails reactjs api rails-activestorage wicked-pdf


    【解决方案1】:

    如果有人对此感兴趣或遇到同样的问题。我希望这可以为您节省一些时间!

    问题出在 axios 请求上。

    代替:

      axios.get(`/v1/invoices/${id}/download`)
    

    使用

      axios.get(`/v1/invoices/${id}/download`, { responseType: 'arraybuffer' })
    

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 2019-06-22
      • 2019-09-26
      • 2021-09-19
      • 2021-12-17
      • 1970-01-01
      • 2020-04-29
      • 2019-11-29
      • 2020-07-29
      相关资源
      最近更新 更多