jQuery HTML5 file drag and drop

前端 未结 3 1209
鱼传尺愫
鱼传尺愫 2021-01-31 21:09

I have looked at many scripts for uploading images to the server with AJAX with drag and drop. The scripts I found are not jQuery, are quite large and don\'t do exactly what I w

3条回答
  •  鱼传尺愫
    2021-01-31 22:11

    törnell

    thanks for sharing you're code, it helped me immensely! For anyone else finding IE edge being a bother here's the final code I have from @jens-törnell and advice given on this post jQuery.on("drop") not firing

      jQuery(document).ready(function($){
        var filename = '';
        var image_data = '';
        $.event.props.push('dataTransfer');
    
        $('.dropzone').on({
          dragover: function(e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).addClass('highlight');
            console.log("t3");
            return false; //crucial for 'drop' event to fire
           },
          dragleave: function(e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).removeClass('highlight');
            return false;
           },
           drop: function(e) {
             e.stopPropagation();
             e.preventDefault();
             var file = e.dataTransfer.files[0];
             var fileReader = new FileReader();
    
             var this_obj = $(this);
    
             fileReader.onload = (function(file) {
                 return function(event) {
                     // Preview
                     filename = file.name;
                     image_data = event.target.result;
                     $(this_obj).next().html('Upload file');
                     $(this_obj).html('');
                 };
             })(file);
             fileReader.readAsDataURL(file);
             return false;
           }
        });
    
        // Upload file
        $(".upload-file").live("click", function(e){
           e.preventDefault();
    
           var this_obj = $(this);
           var image_data = $(this_obj).parent().prev().find('img').attr('src');
    
           $.post(
               'upload-file.php',
               {
                   data: image_data,
                   filename: filename
               }, function(response){
                   $(this_obj).parent().prev().html(response);
                   $(this_obj).remove();
               }
           );
    
         console.log('ok');
     });
      

    Drop files here to upload them.

提交回复
热议问题