编程语言
首页 > 编程语言> > javascript-成功上传后显示上传的图片

javascript-成功上传后显示上传的图片

作者:互联网

我正在Magnific Popup(灯箱)内部使用Carrierwave宝石.我想做的就是上传图片后,它将显示新上传的图片.

目前,从灯箱上传图片后,它将继续显示您最初查看的图片,并显示一条“成功”消息,表示您已成功上传图片.

当前设置是用户单击照片,这将打开包含其画廊照片的灯箱.在灯箱内,您可以删除当前照片,上传新照片或将其设为头像.

photos.js.coffee:

jQuery ->
  $('form#new_photo').fileupload
    dataType: "script"
    add: (e, data) ->
      file = data.files[0]
      data.context = $(tmpl("template-upload", file))
      $('#new_photo').append(data.context)
      data.submit()
    progress: (e, data) ->
      if data.context
        progress = parseInt(data.loaded / data.total * 100, 10)
        data.context.find('.bar').css('width', progress + '%')
    stop: (e, data) ->
      $('.upload').hide()

照片控制器:

 def create
    @photo = Photo.create(params[:photo])
    @photo.user = current_user
    if @photo.save
      flash[:notice] = "Successfully created photos."
      redirect_to :back
    else
      render :action => 'new'
    end
  end

show.html.slim:

   -if @user.photos.present?  
        .slider_container
          h4 Photos
          a.left_arrow href="#" 
            img alt="" src="/assets/left_arrow.png" /
          ul.slider.parent-container
            = hidden_field_tag 'current_index',0
            -@user.photos.each_with_index do |photo, index|
              li class="#{index > 2 ? 'hide' : ''}"
                = link_to image_tag(photo.image_url(:thumb)), "#" + dom_id(photo)
                div id="#{dom_id(photo)}" class="mfp-hide"
                  center
                    = image_tag(photo.image_url(:popup))
                    - if  @user == current_user
                      = button_to('Set as Profile Image', [:avatar, photo], class: 'btn')
                      '
                      = button_to "remove", photo, :confirm => 'Are you sure?', :method => :delete, class: 'btn'
                      = form_for Photo.new do |f|
                        = f.label :image, "Upload photos:"
                        = f.file_field :image, multiple: true, name: "photo[image]"
                      script#template-upload type="text/x-tmpl" 
                        .upload
                          | {%=o.name%}
                          .progress
                            .bar style=("width: 0%") 

解决方法:

我个人更喜欢使用http://blueimp.github.io/jQuery-File-Upload/

>复杂的任务,例如停止上传请求.
>使用浏览器上传而不上传XHR文件
>异步上传

它还具有文档https://github.com/blueimp/jQuery-File-Upload/wiki/API

如果您想自己做,请使用图片网址将json发送回去.

var imageurl = "";
$('#inputValue').attr("src", imageurl);

例如我将输入值绑定到URL

$('#inputName').bind('input',function(){ 
   $('#inputValue').attr("src", $(this).val());
});

演示http://jsfiddle.net/margusmartsepp/83w51u85/

标签:javascript,jquery,ruby-on-rails,ajax,carrierwave
来源: https://codeday.me/bug/20191010/1885471.html