如果你刚好需要在Rails项目中集成一款编辑器,那么我推荐你使用Simditor。轻量级且易用,花个几分钟看一下吧。
//= require jquery
//= require module
//= require hotkeys
//= require uploader
//= require simditor
= require simditor
Git@OSC下载必要的文件
.ui.form = form_for @post do |f| .field = f.text_field :title,:label=>false,:id=>'post_title',:placeholder=>'请输入标题',:class=>'ui transparent input' .field = f.text_area :content,:label=>false .field = f.button :submit,:class=>'ui fluid button' :javascript var editor = new Simditor({ textarea: $('#post_content'), placeholder: '请输入正文', defaultImage: '/image.png', fileKey: 'upload_file', upload: { url: '/upload', leaveConfirm: '正在上传文件,如果离开上传会自动取消' }, pasteImage: true });
在js中
filekey保存上传文件的一些属性(这里的上传文件为图片)
upload属性需要注意的是url: '/upload'这里指明。
根据upload的url:'/upload'我们可以写出对应的request处理路由
post 'upload' => 'upload#image'
到这里前端的任务差不多完成了,最后我们来看一下后端的一些罗辑代码。
class UploadController < ApplicationController def image file = params[:upload_file] file_list = [] success = true msg = '上传成功' file_real_path = '' if !file.content_type.match(/^image\/(gif|png||jpg||jpeg|){1}$/) success = false msg = "#{file.original_filename}:只支持上传JPG,JPEG,PNG格式图片" elsif file.size > 2*1024*1024 success = false msg = "#{file.original_filename}:图片太大,请上传小于2M的图片" end if success file_real_path = save_file(file) file_list << file_real_path end logger.info file_real_path render json: {:success=>success, :msg=>msg,:file_path=>"/#{file_real_path}" } end private def save_file(file) extname = file.content_type.match(/^image\/(gif|png|jpg|jpeg){1}$/).to_a[1] filename = File.basename(file.original_filename,'.*') uri = File.join('uploads','images',"#{DateTime.now.strftime('%Y/%m%d/%H%M%S')}_#{SecureRandom.hex(4)}_#{current_user.id}.#{extname}") save_path = Rails.root.join('public',uri) file_dir = File.dirname(save_path) FileUtils.mkdir_p(file_dir) unless Dir.exists?(file_dir) File.open save_path, 'wb' do |f| f.write(file.read) end return uri end end
这里需要注意的是后端处理之后应返回json,这里是:
render json: {:success=>success, :msg=>msg,:file_path=>"/#{file_real_path}" }
必须要返回插入图片的路径以便在前端页面显示。
提交之后,我们来看一下请求,在下面的日志中,可以仔细看一下上传图片的处理过程。
Started POST "/upload" for 127.0.0.1 at 2015-05-02 03:39:59 +0800 Processing by UploadController#image as */* Parameters: {"upload_file"=>#<ActionDispatch::Http::UploadedFile:0xba34087c @tempfile=#<Tempfile:/tmp/RackMultipart20150502-7561-lbplib.png>, @original_filename="Fruit-2.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"upload_file\"; filename=\"Fruit-2.png\"\r\nContent-Type: image/png\r\n">, "original_filename"=>"Fruit-2.png"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 12 LIMIT 1 uploads/images/2015/0502/033959_a79e85fa_12.png Completed 200 OK in 28ms (Views: 1.0ms | ActiveRecord: 0.2ms) Started POST "/posts" for 127.0.0.1 at 2015-05-02 03:42:00 +0800 Processing by PostsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"dSggdOLs6OvBjtSL9KxuodHnrGmBoX8oWB7FCwuyDFaNGJkDCBl6t8wF2JLe3FT/SWqSHH2pEH1//0Ho0o+/uA==", "post"=>{"title"=>"这是标题", "content"=>"<p><b>粗体 </b> <i>斜体</i> <u>下划线</u> <strike>删除线文字</strike></p><ol><li>有序列表</li><li>有序列表</li></ol><ul><li>无序列表</li><li>无序列表</li></ul><p><img alt=\"Fruit-2.png\" src=\"/uploads/images/2015/0502/033959_a79e85fa_12.png\" data-image-size=\"80,80\"><br></p>"}, "button"=>""} (0.1ms) BEGIN SQL (0.2ms) INSERT INTO `posts` (`tags`, `title`, `content`, `created_at`, `updated_at`) VALUES (NULL, '这是标题', '<p><b>粗体 </b> <i>斜体</i> <u>下划线</u> <strike>删除线文字</strike></p><ol><li>有序列表</li><li>有序列表</li></ol><ul><li>无序列表</li><li>无序列表</li></ul><p><img alt=\"Fruit-2.png\" src=\"/uploads/images/2015/0502/033959_a79e85fa_12.png\" data-image-size=\"80,80\"><br></p>', '2015-05-01 19:42:00.407888', '2015-05-01 19:42:00.407888') (101.7ms) COMMIT Redirected to http://huxi.com/ Completed 302 Found in 107ms (ActiveRecord: 102.1ms)
最后看看Post存储在数据库中的内容
irb(main):008:0> Post.first Post Load (0.3ms) SELECT `posts`.* FROM `posts` ORDER BY `posts`.`id` ASC LIMIT 1 => #<Post id: 4, title: "这是标题", content: "<p><b>粗体 </b> <i>斜体</i> <u>下划线</u> &nb...", visited_count: nil, tags: [], created_at: "2015-05-01 19:42:00", updated_at: "2015-05-01 19:42:00"> irb(main):009:0> Post.first.content Post Load (0.1ms) SELECT `posts`.* FROM `posts` ORDER BY `posts`.`id` ASC LIMIT 1 => "<p><b>粗体 </b> <i>斜体</i> <u>下划线</u> <strike>删除线文字</strike></p><ol><li>有序列表</li><li>有序列表</li></ol><ul><li>无序列表</li><li>无序列表</li></ul><p><img alt=\"Fruit-2.png\" src=\"/uploads/images/2015/0502/033959_a79e85fa_12.png\" data-image-size=\"80,80\"><br></p>" irb(main):010:0>
Over.