图片预览脚本在上传之前删除的相同图片时中断

时间:2016-06-09 13:04:04

标签: javascript jquery jquery-filer

我正在使用这个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."
                }
            }
        });
});

更新

我用html和css以及javascript代码更新了fiddle,遗憾的是我无法让它工作,所以不确定它有多大帮助,但至少你可以看到完整的代码。 我在我上传图片的页面上使用这个脚本:

<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(), 0, 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;
    }

3 个答案:

答案 0 :(得分:0)

我试图在代码中挽救问题部分并提出这个问题(Fiddle)。

问题部分可能在success函数中。不要试图通过索引获取元素,而是使用传递给success函数的第二个参数。

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 );
}

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

答案 1 :(得分:0)

尝试更新到https://innostudio.de/fileuploader/(jQuery.filer已转移到Fileuploader)

答案 2 :(得分:0)

我还使用了具有相同类型问题的JS图像上传器。当用户上传图像并将其删除并再次上传同一图像时,它将不起作用。 因此,我使用以下方法修复了该问题:

$('input[type="file"]').val(null);

在图像删除事件中。