javascript – 上传与之前删除的相同图像时,图像预览脚本会中断

前端之家收集整理的这篇文章主要介绍了javascript – 上传与之前删除的相同图像时,图像预览脚本会中断前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用这个 package,我已经修改了一下,以便我可以上传,拖动和排序图像,并在浏览器中预览.上传工作正常,删除图像.但是当脚本中断时,我发现了一个场景.当我有多个图像,我删除第一个图像,尝试上传相同的图像,我删除的脚本不再工作了.但是,如果我不尝试立即上传相同的图像,并且首先上传其他的图像,然后再删除该图像,那么它可以正常工作.另外,我在控制台中没有任何错误.我不知道如何解决这个问题.

我的完整代码here.

这是代码的一部分:

$(document).ready(function() {

  var imageCounter = 0;

  $('#articleForm').submit(function() {
    uploadPosition();
  });

  function uploadPosition() {
    var uploadedImagesPositions = [];
    $.each($('.jFiler-item-thumb-image'),function( index,value ) {
      $(this).attr('data-position-index',index);
      uploadedImagesPositions[index] = $(this).find('img').attr('src');
    });

    if (! $('input[name="uploadedItems"]').length) {
      $('<input>',{
        type: "hidden",name: "uploadedItems"
      }).appendTo('#articleForm')
    }
    $('input[name="uploadedItems"]').val(JSON.stringify(uploadedImagesPositions));
    $("input[name^='jfiler-items-exclude-']:hidden").detach();
    console.log(uploadedImagesPositions);
  }

   $('#upload').filer({
            limit: null,maxSize: null,extensions: null,changeInput: '<div class="jFiler-input-dragDrop"><h1>+</h1></div>',showThumbs: true,appendTo: '.uploaded_items',theme: "default",templates: {
                Box: '<div class="jFiler-item-list"></div>',item: '<div class="jFiler-item img-container dragdiv"></div>',itemAppend: '<div class="jFiler-item img-container dragdiv"></div>',progressBar: '<div class="bar"></div>',itemAppendToEnd: false,removeConfirmation: false,_selectors: {
                    list: '.jFiler-item-list',item: '.jFiler-item',progressBar: '.bar',remove: '.jFiler-item-trash-action',}
            },uploadFile: {
                url: "/admin/articles/ajax",data: {'_token' : $('input[name="_token"]').val()},type: 'POST',enctype: 'multipart/form-data',beforeSend: function(){},success: function(data,el){
                    uploadedImagesPositions = [];
console.log(data);
                     var filenameArray = data.split('/');
                     var name = filenameArray.slice(-1).pop();
                     var filename = name.replace(/[\/\s()]/g,'');

                     var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();

                     $('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><a href="#"><span><i class="jFiler-item-trash-action ion-trash-a"></span></a></div>').appendTo(imageContainer);
                      imageCounter++;

                      $(".dragdiv").each(function(){
                            makeElementAsDragAndDrop($(this));
                        });

                        $('.images-refresh').hide();
                        $('.images-refresh').click(function(){
                            $(this).closest("form").submit()
                        });

                        function makeElementAsDragAndDrop(elem) {
                            $(elem).draggable({
                                revert: "invalid",cursor: "move",helper: "clone"
                            });
                            $(elem).droppable({
                                activeClass: "ui-state-hover",hoverClass: "ui-state-active",drop: function(event,ui) {
                                    uploadedImagesPositions = [];
                                    $('.images-form a').hide();
                                    $('.images-refresh').show();
                                    var $dragElem = $(ui.draggable).clone().replaceAll(this);
                                    $(this).replaceAll(ui.draggable);
                                    makeElementAsDragAndDrop(this);
                                    makeElementAsDragAndDrop($dragElem);
                                }
                            });
                        }

                    var parent = el.find(".jFiler-jProgressBar").parent();
                    el.find(".jFiler-jProgressBar").fadeOut("slow",function(){
                        $("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
                    });
                },error: function(el){
                    console.log(el);
                    var parent = el.find(".jFiler-jProgressBar").parent();
                    el.find(".jFiler-jProgressBar").fadeOut("slow",function(){
                        $("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
                    });
                },statusCode: {},onProgress: function(){},},dragDrop: {
                dragEnter: function(){},dragLeave: function(){},drop: function(){},addMore: true,clipBoardPaste: true,excludeName: null,beforeShow: function(){return true},onSelect: function(){},afterShow: function(){},onRemove: function(el){
                imageCounter = $('.img-container').size() -1;
                //uploadPosition();
                //console.log(el.find('img').attr('src'));
            },onEmpty: function(){
                imageCounter = 0;
            },captions: {
                button: "Choose Files",Feedback: "Choose files To Upload",Feedback2: "files were chosen",drop: "Drop file here to Upload",removeConfirmation: "Are you sure you want to remove this file?",errors: {
                    filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.",filesType: "Only Images are allowed to be uploaded.",filesSize: "{{fi-name}} is too large! Please upload file up to {{fi-maxSize}} MB.",filesSizeAll: "Files you've choosed are too large! Please upload files up to {{fi-maxSize}} MB."
                }
            }
        });
});

更新

我已经更新了fiddle与html和css以及JavaScript代码,不幸的是我无法让它工作,所以不知道这是多么有用,但至少你可以看到完整的代码.
我在我上传图片页面上使用这个脚本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ asset('js/foundation/foundation.min.js') }}"></script>
<script>$(document).foundation();</script>
<script type="text/javascript" src="{{ asset('js/jquery-ui/jquery-ui.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-filer/jquery-filer.js') }}"></script>

jquery-filer是我用于上传的脚本,我用的是脚本.

这是我的服务端功能,用于ajax上传.我在后台使用PHP laravel:

public function ajaxUpload() {

        if (Input::hasFile('file')) {
            $files = Input::file('file');

            foreach ($files as $file) {
                $time = microtime(true);
                $name = $file->getClientOriginalName();
                $filename = $time.'-'.preg_replace('/[(\)\s]/u','',$name);

                if(substr($file->getMimeType(),5) == 'image') {

                    try {
                        $original = Image::make($file)->save(public_path($this->destinationPath.'/'.$filename));
                        \Log::info('try: '.$filename."\n");

                    } catch (Exception $e) {
                        \Log::info('Caught exception: '.$e->getMessage(). "\n");
                    }

                    $img = Image::cache(function($image) use ($original){
                        return $image->make($original);
                    });
                }
            }
        }

        return $this->destinationPath.$filename;
    }

解决方法

我试图在你的代码解决问题的一部分,并提出了这个( Fiddle).

问题部分可能在成功的功能.而不是尝试通过索引获取元素,使用传递给成功函数的第二个参数.

success: function(data,el) {
  uploadedImagesPositions = [];
  var filenameArray = data.split('/');
  var name = filenameArray.slice(-1).pop();
  var filename = name.replace(/[\/\s()]/g,'');

  // Instead of this
  // var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();

  // Use this
  var imageContainer = el;

  $('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><a href="#"><span><i class="jFiler-item-trash-action ion-trash-a"></span></a></div>').appendTo(imageContainer );
}

该问题也可能是由您的服务器端造成的,我们现在无法访问.

猜你在找的JavaScript相关文章