最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to show remove button and remove uploaded file? - Stack Overflow

programmeradmin3浏览0评论

Please help me I'm trying to create file uploading with dropzone.js and I am having so much hard time finding a way how to remove uploaded files. This is my code:

index.php

<div class="container">
<div class="file_upload">
    <form action="file_upload.php" class="dropzone">
        <div class="dz-message needsclick">
            <strong>Drop files here or click to upload.</strong><br />
        </div>
    </form>     
</div>      

file-upload.php

include_once("db_connect.php");
if(!empty($_FILES)){     
    $upload_dir = "uploads/";
    $fileName = $_FILES['file']['name'];
    $uploaded_file = $upload_dir.$fileName;    
    if(move_uploaded_file($_FILES['file']['tmp_name'],$uploaded_file)){
        //insert file information into db table
        $mysql_insert = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
        mysqli_query($conn, $mysql_insert) or die("database error:". mysqli_error($conn));
    }   
}

How can I put a remove button and remove the uploaded file?

Please help me I'm trying to create file uploading with dropzone.js and I am having so much hard time finding a way how to remove uploaded files. This is my code:

index.php

<div class="container">
<div class="file_upload">
    <form action="file_upload.php" class="dropzone">
        <div class="dz-message needsclick">
            <strong>Drop files here or click to upload.</strong><br />
        </div>
    </form>     
</div>      

file-upload.php

include_once("db_connect.php");
if(!empty($_FILES)){     
    $upload_dir = "uploads/";
    $fileName = $_FILES['file']['name'];
    $uploaded_file = $upload_dir.$fileName;    
    if(move_uploaded_file($_FILES['file']['tmp_name'],$uploaded_file)){
        //insert file information into db table
        $mysql_insert = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
        mysqli_query($conn, $mysql_insert) or die("database error:". mysqli_error($conn));
    }   
}

How can I put a remove button and remove the uploaded file?

Share Improve this question edited Sep 19, 2017 at 15:27 codtex 6,5582 gold badges20 silver badges36 bronze badges asked Sep 19, 2017 at 6:21 JBAJBA 2376 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

METHOD 1

There is a build in functionality in the library that you can use.

  • addRemoveLinks option - see also the bold props

If true, this will add a link to every file preview to remove or cancel (if already uploading) the file. The dictCancelUpload, dictCancelUploadConfirmation and dictRemoveFile options are used for the wording.

  • dictRemoveFileConfirmation option

If this is not null, then the user will be prompted before removing a file.

With the bination of those two properties you will have the build in remove links with confirmation message(specified in dictRemoveFileConfirmation) which will remove the file from the user interface and to remove it also from the server side you can send AJAX request from removedfile event subscription. For example:

removedfile

Called whenever a file is removed from the list. You can listen to this and delete the file from your server if you want to.

myDropzone.on('removedfile', function (file) {

    console.log(file);
    /* here do AJAX call to your server ... */

});

/* flag is used for testing purpose - to demostrate success and failuer on server */
var flag = false;
Dropzone.options.myAwesomeDropzone = {
  url: '/upload',
  addRemoveLinks: true,
  dictRemoveFileConfirmation: 'Are you sure that you want to remove this file?',
  init: function() {
    var dz = this;
    dz.on('removedfile', function(file) {
      flag = !flag;
      console.log('file ' + file.name + ' was removed from front-end  ...');
      doAjaxCall(flag).then(function() {
        console.log('file ' + file.name + ' was removed from back-end  ...');
      }, function() {
        console.log('failed to remove file ' + file.name + ' from back-end  ...');
        /* this is a way to restore the file on the front-end
           if something fails on the back-end */
        dz.emit('addedfile', file);
        dz.emit('plete', file);
      });
    });
  }
}

function doAjaxCall(flag) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      flag ? resolve() : reject();
    }, 1000);
  });
}
<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/dropzone/5.1.1/min/basic.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/dropzone/5.1.1/min/dropzone.min.css" />
<script src="https://cdnjs.cloudflare./ajax/libs/dropzone/5.1.1/min/dropzone.min.js"></script>

<p>If you upload two files and try to remove them first will demostrate success on server and the second will demostrate failure on server</p>
<div class="dropzone" id="my-awesome-dropzone"></div>

METHOD 2

Using a custom theme. Dropzonejs allows you to have a totally custom layout and allows you to overwrite all the default event handlers - then you can fully control the behavior of your dropzone :)

Take a look on that sample.

So basically each dropzone has the following default layout:

<div class="dz-preview dz-file-preview">
  <div class="dz-details">
    <div class="dz-filename"><span data-dz-name></span></div>
    <div class="dz-size" data-dz-size></div>
    <img data-dz-thumbnail />
  </div>
  <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
  <div class="dz-success-mark"><span>✔</span></div>
  <div class="dz-error-mark"><span>✘</span></div>
  <div class="dz-error-message"><span data-dz-errormessage></span></div>
</div>

This layout is specified in options previewTemplate option. So what you can do to have a custom remove button is to add element in the template that contains the attribute data-dz-remove, for example:

<!-- Following button with use the build-in functionality 
     since it has the attribute data-dz-remove -->
<div data-dz-remove class="my-remove-button"></div> 

But if you want more control, for example to make the AJAX call to server and on successful response to remove the file, you can do it again with custom previewTemplate and control events by yourself:

var flag = false;
var previewTemplate = 
'<li class="dz-preview dz-file-preview">' +
  '<div class="dz-details">' +
  '  <div class="dz-filename">' +
  '    <span data-dz-name></span>' +
  '    (<span data-dz-size></span>)' +
  '    <span class="btn-remove">Remove</span>' +
  '</div>' +
  '</div>' +
  '<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>' +
  '<div class="dz-error-message"><span data-dz-errormessage></span></div>' +
'</li>';

Dropzone.options.myAwesomeDropzone = {
  url: '/upload',
  previewTemplate: previewTemplate,
  previewsContainer: '#preview-container',
  init: function() {
    var dz = this;
    dz.on('addedfile', function(file){
      var btnRemove = file.previewElement.querySelector('.btn-remove');
      btnRemove.fileRef = file;
      btnRemove.addEventListener('click', function(e){
        var button = this;
        flag = !flag;
        var keyword = flag ? 'succeed' : 'fail';
        console.log('Sending ajax call that will ' + keyword);
        doAjaxCall(flag).then(function(){
          dz.removeFile(button.fileRef);
          button.fileRef = null;
          console.log('File was removed successfully !');
        }, function(){
          console.log('File was removal failed !');
        });
       
      });
    });
  }
}

function doAjaxCall(flag) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      flag ? resolve() : reject();
    }, 1000);
  });
}
.btn-remove{
  background-color: red;
  color: white;
  font-weight: bold;
  text-align: center;
  border-radius: 5px;
  padding: 3px;
}

.btn-remove:hover{
  cursor: pointer;
}

.dropzone{
  height: 70px;
  background-color: blue;
  color: white;
  border-radius: 10px;
}

.dropzone .dz-default.dz-message span{
  display: block;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding-top: 20px;
}

.dz-preview{
  margin-bottom:5px;
}
<script src="https://cdnjs.cloudflare./ajax/libs/dropzone/5.1.1/min/dropzone.min.js"></script>

<div id="my-awesome-dropzone" class="dropzone"></div>
<ul id="preview-container"></ul>

<div class="my-remove-button"></div> 

Javascript

myDropzone.on('plete', function (file) {
    /* store reference to the file on upload pleted */
    file.previewElement.querySelector('.my-remove-button').fileRef = file;
});

document.querySelector('.my-remove-button').onclick = function () {
    doAjaxCall().then(function(response){
        /* use the previously stored reference to remove the file 
           if successfully removed the file from server */
        if(response.result){
            if(this.fileRef){
                myDropzone.removeFile(this.fileRef);
                this.fileRef = null;                 
            }
        }
    });

};

Just set addRemoveLinks to true.

//"myDropzone" is the camelized version of the form ID
Dropzone.options.myDropzone = {
    addRemoveLinks: true,
};
发布评论

评论列表(0)

  1. 暂无评论