首先,我使用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中本地存储。为了进行测试,我还在开发人员中使用了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)
我可以将该网址发送回前端,并在新标签页中打开它以查看pdf。但这不是我想要的...
谢谢你的帮助!
如果有人对此感兴趣或遇到相同的问题。希望这可以节省您一些时间!
问题出在axios请求上。
代替:
axios.get(`/v1/invoices/${id}/download`)
采用
axios.get(`/v1/invoices/${id}/download`, { responseType: 'arraybuffer' })
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句