ruby-on-rails - Rails API / react / axios 下载损坏的文件
问题描述
首先,我用 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' })
推荐阅读
- stack-trace - 如何在 Nest.js 中参考打字稿源打印堆栈跟踪
- ajax - 如何在 TYPO3 中使用 ext:typoscript_rendering 和 ext:from
- c# - ValueTuple 通过反射设置字段
- zurb-foundation - Foundation 6 自定义构建生成不起作用
- dart - 如何使终端中的“pub”命令可用?
- c# - 将 .netframework NserviceBus 端点服务迁移到 .net core 3.0
- svn - TortoiseSVN 用户指南死链接?
- java - Spring Boot 自定义运行状况指示器未显示
- php - 基于 if 语句定义 $variable
- javascript - Google chrome DOMException:navigator.mediaDevices.getUserMedia 的权限被系统拒绝