---
title: "利用paperclip实现kindEditoer的图片上传和浏览"
author: "jackdong"
date: "2010-08-25T10:11:29Z"
tags: []
categories: ["编程语言"]
slug: "paperclip-kindeditoer"
draft: false
lastmod: "2010-08-25T10:11:29Z"
id: 746577
url: "https://dnnta.iteye.com/blog/746577"
---

[**KindEditor**](http://www.kindsoft.net/index.php)是一款优秀的开源HTML编辑器， 它的图片上传和浏览是利用插件的方式进行的。编辑器的参数中imageUploadJson定义了图片上传的后台程序地址， allowFileManager 定义了是否允许浏览服务器图片,fileManagerJson指定了浏览图片时后台程序地址。以下代码根据个人情况应该有所不同。

 

 写道

{"error":1, "url":"URL"}图片上传成功返回的字符串  
{"error":0} 上传失败返回的字符串

 下面是KindEditor Demo里面后台地址返回的json字符串。图片浏览是通过plugins/file\_manager/file\_manager.js来解析服务器端返回的json字符串的。

 

由于我们的图片是通过[**paperclip**](http://github.com/thoughtbot/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"}]}

 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
```