簡體   English   中英

Rails API / react / axios 下載損壞的文件

[英]Rails API / react / axios downloads corrupted file

首先,我用 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

我的前端(反應)使用 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。 但這不是我想要的……

謝謝你的幫助!

如果有人對此感興趣或遇到同樣的問題。 我希望這會為您節省一些時間!

問題在於 axios 請求。

代替:

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

利用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM