KindEditor是一款优秀的开源HTML编辑器, 它的图片上传和浏览是利用插件的方式进行的。编辑器的参数中imageUploadJson定义了图片上传的后台程序地址, allowFileManager 定义了是否允许浏览服务器图片,fileManagerJson指定了浏览图片时后台程序地址。以下代码根据个人情况应该有所不同。
写道
{"error":1, "url":"URL"}图片上传成功返回的字符串
{"error":0} 上传失败返回的字符串
下面是KindEditor Demo里面后台地址返回的json字符串。图片浏览是通过plugins/file_manager/file_manager.js来解析服务器端返回的json字符串的。
{"error":0} 上传失败返回的字符串
由于我们的图片是通过paperclip来进行上传处理的,因此图片都是以一定格式比如/datas/:id/:style存放,而kindeditor的Demo中图片时存在在一个文件夹里的。通过阅读这个js文件,发现在服务器在返回时把图片的路径设置在dir_path里就可以一次返回不同文件夹里的图片。把moveup_dir_path、current_dir_path、current_url、total_count这几个参数也基本没有用处,可以直接54。我们直接返回需要用到的filename, filesize, dir_path和datetime就可以了,代码见下面。
写道
{"moveup_dir_path":"","current_dir_path":"","current_url":"\/ke\/php\/..\/attached\/",
"total_count":5,"file_list":[{"is_dir":false,"has_file":false,"filesize":208736,
"dir_path":"","is_photo":true,"filetype":"jpg",
"filename":"1241601537255682809.jpg","datetime":"2009-12-10 09:18:36"}]}
"total_count":5,"file_list":[{"is_dir":false,"has_file":false,"filesize":208736,
"dir_path":"","is_photo":true,"filetype":"jpg",
"filename":"1241601537255682809.jpg","datetime":"2009-12-10 09:18:36"}]}
upload为访问imageUploadJson所定义的程序地址后台调用action,同理images_list为fileManagerJson所定义后台action,应根据个人配置做相应的调整。
#model
class Image < ActiveRecord::Base has_attached_file :data :style=>{:medium =>"300x300>", :thumb => "100x100>"}
end
#controller
class Admin::ImagesController < Admin::BaseController
protect_from_forgery :except => :upload
def upload
@image = Image.new(:data => params[:imgFile])
if @image.save
render :text => {"error" => 0, "url" => @image.data_url(:medium)}.to_json
else
render :text => {"error" => 1}
end
end
def images_list
@images = Image.all
@json = []
for image in @images
temp = %Q/{"filesize" : #{image.data_size},
"filename" : "#{image.filename}",
"dir_path" : "#{image.data_url(:small)}",
"datetime" : "#{image.created_at}"}/
@json << temp end render :text => ("{\"file_list\":[" << @json.join(", ") << "]}")
end
end
#plugins/file_manager/file_manager.js
#createView 以缩略图形式创建试图
#createList 以列表形式创建视图
#var fileUrl = result.current_url + data.filename; fileUrl为缩略图的地址,我们不返回current_url,因为替换如下
var fileUrl = result.dir_path
#无is_dir和is_photo返回,因为只是返回单一图片,可以直接设置
#var iconUrl = data.is_dir ? './images/folder-64.gif' : (data.is_photo ? fileUrl : './images/file-64.gif');
iconUrl = fileUrl