Programing

업로드되는 dropzone.js 파일 수를 제한하는 방법은 무엇입니까?

crosscheck 2020. 11. 6. 07:52
반응형

업로드되는 dropzone.js 파일 수를 제한하는 방법은 무엇입니까?


사용 사례에 따라 dropzone.js가 허용하는 파일 수를 어떻게 제한합니까?

예를 들어 1, 2 또는 4 개의 파일 만 업로드하도록 허용해야 할 수 있습니다.

아니에요 uploadMultiple. 안타깝게도 uploadMultiple요청 당 처리되는 파일 수에만 적용됩니다.


나는 이것을 약간 다른 방식으로 달성했습니다. 새 파일이 추가 될 때마다 이전에 드롭 된 파일을 제거합니다. 여기에서 내가 원하는 사용자 경험이었던 파일을 덮어 쓰는 역할을합니다.

Dropzone.options.myAwesomeDropzone = {
  accept: function(file, done) {
    console.log("uploaded");
    done();
  },
  init: function() {
    this.on("addedfile", function() {
      if (this.files[1]!=null){
        this.removeFile(this.files[0]);
      }
    });
  }
};

Nowell은이 문제가 2013 년 8 월 6 일 현재 해결되었다고 지적했습니다 .이 양식을 사용하는 실제 예제는 다음과 같습니다.

<form class="dropzone" id="my-awesome-dropzone"></form>

이 JavaScript를 사용할 수 있습니다.

Dropzone.options.myAwesomeDropzone = {
  maxFiles: 1,
  accept: function(file, done) {
    console.log("uploaded");
    done();
  },
  init: function() {
    this.on("maxfilesexceeded", function(file){
        alert("No more files please!");
    });
  }
};

dropzone 요소는 특별한 스타일을 가지므로 다음과 같은 작업을 수행 할 수 있습니다.

<style>
  .dz-max-files-reached {background-color: red};
</style>

가장 직관적 인 단일 파일 업로드 프로세스는 새 항목으로 이전 파일 교체 하는 것이라고 생각했습니다 .

  $(".drop-image").dropzone({
    url: '/cart?upload-engraving=true',
    maxFiles: 1,
    maxfilesexceeded: function(file) {
        this.removeAllFiles();
        this.addFile(file);
    }
})

maxFiles: 1작업을 수행하지만 추가 파일도 제거하려면 Wiki 페이지 에서 가져온 다음 샘플 코드를 사용할 수 있습니다 .

파일 수를 제한하려면 어떻게합니까?

당신은 운이 좋다! 3.7.0부터 Dropzone은 maxFiles 옵션을 지원합니다. 원하는 수량으로 설정하기 만하면됩니다. 거부 된 파일을 보지 않으려면 maxfilesexceeded 이벤트에 등록하고 즉시 파일을 제거하십시오.

myDropzone.on("maxfilesexceeded", function(file)
{
    this.removeFile(file);
});

나를 위해 정말 잘 작동하는 대체 솔루션 :

init: function() {
    this.on("addedfile", function(event) {
        while (this.files.length > this.options.maxFiles) {
            this.removeFile(this.files[0]);
        }
    });
}

maxFiles가 찾고있는 매개 변수 인 것 같습니다.

https://github.com/enyo/dropzone/blob/master/src/dropzone.coffee#L667


dropezone.js에서 변경하여 업로드되는 파일 수를 제한 할 수 있습니다.

Dropzone.prototype.defaultOptions = {maxFiles : 10,}


클릭 이벤트를 비활성화하기 위해 CSS를 사용하지 않는 이유는 무엇입니까? 최대 파일에 도달하면 Dropzone은 자동으로 dz-max-files-reached 클래스를 추가합니다.

css를 사용하여 dropzone 클릭을 비활성화하십시오.

.dz-max-files-reached {
          pointer-events: none;
          cursor: default;
}

크레딧 :이 답변


제공된 솔루션의 문제점은 1 개의 파일 만 업로드 할 수 있다는 것입니다. 제 경우에는 한 번에 하나의 파일 만 업로드해야했습니다 (클릭 또는 드롭시).

이것이 제 해결책이었습니다 ..

    Dropzone.options.myDropzone = {
        maxFiles: 2,
        init: function() {
            this.handleFiles = function(files) {
                var file, _i, _len, _results;
                _results = [];
                for (_i = 0, _len = files.length; _i < _len; _i++) {
                    file = files[_i];
                    _results.push(this.addFile(file));
                    // Make sure we don't handle more files than requested
                    if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
                        break;
                    }
                }
                return _results;
            };
            this._addFilesFromItems = function(items) {
                var entry, item, _i, _len, _results;
                _results = [];
                for (_i = 0, _len = items.length; _i < _len; _i++) {
                    item = items[_i];
                    if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) {
                        if (entry.isFile) {
                            _results.push(this.addFile(item.getAsFile()));
                        } else if (entry.isDirectory) {
                            _results.push(this._addFilesFromDirectory(entry, entry.name));
                        } else {
                            _results.push(void 0);
                        }
                    } else if (item.getAsFile != null) {
                        if ((item.kind == null) || item.kind === "file") {
                            _results.push(this.addFile(item.getAsFile()));
                        } else {
                            _results.push(void 0);
                        }
                    } else {
                        _results.push(void 0);
                    }
                    // Make sure we don't handle more files than requested
                    if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
                        break;
                    }
                }
                return _results;
            };
        }
    };

도움이 되었기를 바랍니다 ;)


지적하고 싶습니다. 아마도 이것이 나에게 일어날 수도 있지만, dropzone에서 this.removeAllFiles ()를 사용하면 COMPLETE 이벤트가 발생하고 이것이 불면 fileData가 비어 있는지 여부를 확인하여 실제로 양식을 제출할 수 있습니다.


You can also add in callbacks - here I'm using Dropzone for Angular

dzCallbacks = {
    'addedfile' : function(file){
        $scope.btSend = false;
        $scope.form.logoFile = file;
    },
    'success' : function(file, xhr){
        $scope.btSend = true;
        console.log(file, xhr);
    },
    'maxfilesexceeded': function(file) {
         $timeout(function() { 
            file._removeLink.click();
        }, 2000);
    }
}

Dropzone.options.dpzSingleFile = {
    paramName: "file", // The name that will be used to transfer the file
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    }
};

참고URL : https://stackoverflow.com/questions/18048825/how-to-limit-the-number-of-dropzone-js-files-uploaded

반응형