【问题标题】:Backbone + Rails 'Paperclip' Async UploadsBackbone + Rails 'Paperclip' 异步上传
【发布时间】:2023-03-22 01:19:01
【问题描述】:

我正在使用骨干网和 rails 'paperclip' gem 实现异步照片上传:

问题:

  1. 我需要使用 jQuery 上传(或等效库)吗?
  2. 如果是这样,我是否只需覆盖 photocollection.sync 来调用库?

项目.rb

class Item < ActiveRecord::Base
   has_many: photos
   ...

照片.rb

class Photo < ActiveRecord::Base

  attr_accessible :photo
  belongs_to :item

  has_attached_file :photo
...

ItemView.js.coffee

class MySite.Views.Items.Edit extends Backbone.View

  template: JST['items/edit']

  initialize: ->
    @modelBinder = new Backbone.ModelBinder
    @model.on('change', @render(), this)

  events: ->
    'submit #edit_item_form' : 'save_item'

  render: ->
    $(@el).html @template( item: @model )

    @new_photo = @model.new_photo()

    @modelBinder.bind @model, $("#item_fields")
    @modelBinder.bind @new_photo, $("#photo_fields")
    @

  save_item: (e) ->
    e.preventDefault()
    @model.save()
    @new_photo.save()

Edit.jst.eco

<form id="edit_item_form" accept-charset="UTF-8" data-remote="true" enctype="multipart/form-data">
<div id="item_fields"> .... </div>
<div id="photo_fields">
   <input type="file" id="upload_photo" name="photo[photo]" />
</div>
...

欢迎提出整体设计改进建议

【问题讨论】:

    标签: ruby-on-rails backbone.js coffeescript paperclip ajax-upload


    【解决方案1】:

    我最终选择了 iframe 上传的简单性和跨浏览器支持。实现其实很简单:

    MyView.js.coffee:

      events: ->
        'change #upload_photos' : 'upload_photo'
    
      upload_photo: (e) ->
        upload_frame = $('#add_photo_form')
        upload_frame.prop 'target', 'upload_frame'
        upload_frame.submit()
    

    MyTemplate.jst.eco:

    <form id="add_photo_form" method="POST" action="/api/v1/photos" enctype="multipart/form-data">
      <div id="photo_fields">
          <input type="file" id="upload_photos" name="photo[photo]" multiple>
          <input type="hidden" name="authenticity_token" value="<%= $("meta[name='csrf-token']").attr("content") %>">
      </div>
    </form>
    <iframe id='upload_frame' name='upload_frame' src=''></iframe>
    

    注意添加了 CSRF Token。没有它,请求将失败并清除您的会话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-04
      • 2017-09-03
      • 2011-11-12
      • 2014-07-17
      • 1970-01-01
      • 2012-09-23
      • 2013-12-29
      • 1970-01-01
      相关资源
      最近更新 更多