1

我有一个Post模型:

  create_table "posts", :force => true do |t|
    t.string   "title"
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at",                            :null => false
    t.datetime "updated_at",                            :null => false
    t.integer  "comments_count",     :default => 0,     :null => false
    t.boolean  "published",          :default => false
    t.datetime "published_at"
    t.boolean  "draft",              :default => false
  end

这是它的形式:

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
  <%= render 'shared/error_messages' %>
  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %>
    <%= f.text_area :content %>
  </div>

  <div class="field">
    <%= f.label :draft %>
    <%= f.check_box :draft %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我正在寻找一种从.doc, .docx, and rtf文件中获取文本并将它们显示到content文本字段中的方法(因此用户不必打开他的文件、复制文本并将其粘贴到表单中)。

有什么建议么?

(是否有任何 gem、文本编辑器或 jQuery 插件可以做到这一点?)?

编辑:

卡在这里:

post.rb:

class Post < ActiveRecord::Base
  require 'docx'
  .
  .
  .  
  def read_docx
    d = Docx::Document.open(self.document)
    d.each_paragraph do |p|
      puts d
    end
  end
end

post_controller.rb:

class PostsController < ApplicationController
  before_filter :authenticate_user!, :except => [:show, :index]
  .
  .
  .
  def create
    @user = current_user
    @post = @user.posts.new(params[:post])
    @doc_text = (no idea what to do here)

    if @post.save
      redirect_to @post, notice: 'post was successfully created.'
    else
      render action: "new"
    end
  end

  def edit
    @post = Post.find(params[:id])
  end
  .
  .
  .

帖子/new.html.erb:

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
  <%= render 'shared/error_messages' %>
  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %>
    <%= f.text_area :content, :value => @doc_text %>
  </div>
  .
  .
  .

我已经制作了回形针上传 docx 文件

我创建了一个名为:document

4

1 回答 1

3

好吧,我刚刚尝试了docx gem,它工作正常。您可以在其 github 页面上获得 2 个示例。遗憾的是,它不适用于 doc 文件。

对于他们,您可以在此处使用此宝石。github 页面上有一些示例,但是如果您想获取 doc 文件的全部内容,请执行以下操作:

require 'msworddoc-extractor'

MSWordDoc::Extractor.load('sample.doc') do |doc|
  puts doc.whole_contents
end

您还可以调用其他方法doc,例如documentheader。再次,检查 github 页面。

对于 rtf,您也可以使用这个gem

现在,在里面传递它content很容易。只需定义如何从文件中获取数据,例如在控制器上调用的外部库:

@doc_text = Parser.doc("file.doc")
@docx_text = Parser.docx("file.docx")
@rtf_text = Parser.rtf("file.rtf")

或者直接或通过您想到的任何方法获取值。要在视图中显示它,您只需添加:value如下选项:

<%= f.text_area :content, :value => @doc_text %> 
#Where @doc_text is the data from file
于 2012-10-21T03:09:50.670 回答