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

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

作者: waynedeng | 来源:发表于2016-05-22 20:47 被阅读312次

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

    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下面的代码。

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/aetarttx.html