dongrang2140 2017-09-19 06:21
浏览 278

如何显示删除按钮并删除上传的文件?

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?

  • 写回答

2条回答 默认 最新

  • dongliyun3301 2017-09-19 07:09
    关注

    METHOD 1

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

    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.

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

    With the combination 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('complete', file);
          });
        });
      }
    }
    
    function doAjaxCall(flag) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          flag ? resolve() : reject();
        }, 1000);
      });
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.1.1/min/basic.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.1.1/min/dropzone.min.css" />
    <script src="https://cdnjs.cloudflare.com/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.com/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('complete', function (file) {
        /* store reference to the file on upload completed */
        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;                 
                }
            }
        });
    
    };
    
    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改