Chrome中如何拖拽和粘贴自动上传图片(Rails实现)

2016-05-22  本文已影响312人  waynedeng

项目需求,有这样的功能上传图片方便许多,而且简书的编辑器就有同样的功能哦!

Paste_Image.png

在Rails中的使用:

1、简单起见,把jQuery和InlineAttachment的两个js文件放在public下面(当然正常来说应该放在assets/javascripts下面);

2、创建控制器;

    class UploadController < ApplicationController

      protect_from_forgery :except => :upfile

      def index
        render :layout => nil
      end
              
      # 上传文件
      def upfile
        if file = params[:file]

          if !file.original_filename.empty?
            @filename = file.original_filename

            FileUtils.mkdir("#{Rails.root}/public/upload") unless File.exist?("#{Rails.root}/public/upload")
            #写入文件
            File.open("#{Rails.root}/public/upload/#{@filename}", "wb") do |f|
              f.write(file.read)
            end
            render :json=>{filename: "/upload/#{@filename}"}
          else
            render :json=>{error: 'Upload error!'}
          end
        else
          render :json=>{error: 'Upload error!'}
        end
      end

    end

3、路由

  get 'upload/index'

  post 'upload/upfile'

4、视图 index.rhtml

    <!DOCTYPE html>
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>jQuery InlineAttachment Demo</title>
    </head>
    <body>
    <textarea rows="10" cols="50"></textarea>
    <textarea rows="10" cols="50"></textarea>
    <textarea rows="10" cols="50"></textarea>

    <script src="/jquery-1.7.1.min.js"></script>
    <script src="/inline-attachment.min.js"></script>
    <script src="/jquery.inline-attachment.min.js"></script>


    <script type="text/javascript">
      $(function() {
        $('textarea').inlineattachment({
          uploadUrl: '/upload/upfile'
        });
      });
    </script>
    </body>
    </html>

结束!如果想了解具体的实现,可以查看src下面的代码。

上一篇下一篇

猜你喜欢

热点阅读