gpt4 book ai didi

ruby-on-rails - Backbone + Rails 'Paperclip' 异步上传

转载 作者:行者123 更新时间:2023-12-03 12:18:53 27 4
gpt4 key购买 nike

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

问题:

  • 我需要使用 jQuery 上传(或等效的库)吗?
  • 如果是这样,我是否只需覆盖 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()

    编辑.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>
    ...

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

    最佳答案

    我最终选择了 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 的添加。没有它,请求将失败并清除您的 session 。

    关于ruby-on-rails - Backbone + Rails 'Paperclip' 异步上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100393/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com