【问题标题】:How can I view a pdf file that is encoded (as base64) in my database?如何查看在我的数据库中编码(作为 base64)的 pdf 文件?
【发布时间】:2013-08-09 05:36:18
【问题描述】:

我目前在 heroku 上有一个站点,并且正在使用 postgreSQL。当我将 pdf 文件上传到数据库时,我将它们编码为 base64 并将它们保存为文本。我可以单击链接解码文件并毫无问题地下载;但是,我遇到了一个页面,其中有一个 iframe,其中包含 pdf 文件。如何将新解码的文件提供给 iframe?即使没有 iframe,我如何才能将文件解码并作为页面使用?

我在想我可以创建一个 pdf 控制器,解码文件并显示打开文件,但我什至无法让它工作。

感谢您的帮助!

编辑:这是我目前所拥有的。

def create
  @course = Course.find(params[:note][:id])
  params[:note][:content].tempfile = Base64.encode64(open(params[:note][:content].tempfile).to_a.join)
  params[:note][:filename] = params[:note][:content].original_filename
  params[:note][:contenttype] = params[:note][:content].content_type
  @note = @course.notes.build(:content => params[:note][:content].tempfile, :filename => params[:note][:filename],        
  :contenttype => params[:note][:contenttype])
  if @note.save
      flash[:success] = "File Uploaded!"
      redirect_to root_path
end

这将文件保存为 base64 没有问题。不过我不太确定下一部分。

def show
  @note = Note.find(params[:id])
  @notecon = @note.content
  decoded_data=Base64.decode64(@notecon)
  file_name = "test"
  @temp_file = Tempfile.new("filename-#{Time.now}")
  File.open(@temp_file, 'wb') {|f| f.write(decoded_data)}
end

现在,在视图中,我不知道将什么作为文件路径。

<iframe src="http://docs.google.com/gview?url=http://localhost:3000/app/views/notes/test&embedded=true" 
style="width:718px; height:700px;" frameborder="0"></iframe>

我什至不知道如何发布保存在我的驱动器上的 pdf 文件。 再次感谢!

【问题讨论】:

  • 向我们展示您到目前为止所做的事情,如果没有起点,很难帮助您。

标签: ruby-on-rails postgresql iframe heroku


【解决方案1】:

你可以使用

send_data 

动作控制器中的方法将文件发送到浏览器。您需要设置内容类型、浏览器的显示方式等。

send_data(@pdf, :type => 'application/pdf', :filename => "myfile.pdf", :disposition => "inline"

:deposition=>'inline' 指示浏览器将其显示在浏览器内部。

您可以在此处找到类似的示例,他们将图像上传到数据库

http://over9000.org/rails/saving-ruby-on-rails-attachments-as-blobs

https://gist.github.com/macek/610596

Rails: Storing binary files in database

考虑将 pdf 存储到 Amazon S3 存储桶或其他云存储中。 PaperClip gem 可以透明地为您完成。 https://github.com/thoughtbot/paperclip‎。回形针也可以保存到数据库。

如果您仍打算使用数据库存储,请注意其缺点 Rails: Storing binary files in database

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多