Ruby on rails Rails API/react/axios下载损坏的文件
首先,我用WickedPDF创建了一个pdfRuby on rails Rails API/react/axios下载损坏的文件,ruby-on-rails,reactjs,api,rails-activestorage,wicked-pdf,Ruby On Rails,Reactjs,Api,Rails Activestorage,Wicked Pdf,首先,我用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:
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。但这不是我想要的
谢谢你的帮助 以防有人对此感兴趣或遇到相同的问题。我希望这能为你节省一些时间 问题在于axios请求 而不是:
axios.get(`/v1/invoices/${id}/download`)
使用
以防有人对此感兴趣或遇到相同的问题。我希望这能为你节省一些时间 问题在于axios请求 而不是:
axios.get(`/v1/invoices/${id}/download`)
使用