[javascript] blueimp 파일 업로드 플러그인의 maxFileSize 및 acceptFileTypes가 작동하지 않습니다. 왜?

업로드 파일에 Blueimp jQuery 파일 업로드 플러그인을 사용하고 있습니다.

나는 업로드하지만 옵션에는 문제가 없었다 maxFileSizeacceptFileTypes작업을하지 않습니다.

이것은 내 코드입니다.

$(document).ready(function () {
    'use strict';

    $('#fileupload').fileupload({
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 5000000,
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
                    .appendTo('#div_files');
            });
        },
        fail: function (e, data) {
            $.each(data.messages, function (index, error) {
                $('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
                    .appendTo('#div_files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);

            $('#progress .bar').css('width', progress + '%');
        }
    });
});



답변

같은 문제가 있었고 blueimp 사람은 ” maxFileSize 및 acceptFileTypes는 UI 버전에서만 지원됩니다 “라고 말하고 _validate 및 _hasError 메소드를 통합하기위한 (깨진) 링크를 제공했습니다.

그래서 스크립트를 엉망으로 만들지 않고 이러한 방법을 통합하는 방법을 모르고이 작은 함수를 작성했습니다. 그것은 나를 위해 일하는 것 같습니다.

그냥 추가하세요

add: function(e, data) {
        var uploadErrors = [];
        var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('Not an accepted file type');
        }
        if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize is too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.submit();
        }
},

여기에 코드에 표시된대로 .fileupload 옵션 시작 부분

$(document).ready(function () {
    'use strict';

    $('#fileupload').fileupload({
        add: function(e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                    uploadErrors.push('Not an accepted file type');
                }
                if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if(uploadErrors.length > 0) {
                    alert(uploadErrors.join("\n"));
                } else {
                    data.submit();
                }
        },
        dataType: 'json',
        autoUpload: false,
        // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        // maxFileSize: 5000000,
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
                .appendTo('#div_files');
            });
        },
        fail: function (e, data) {
            $.each(data.messages, function (index, error) {
                $('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
                .appendTo('#div_files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);

            $('#progress .bar').css('width', progress + '%');
        }
    });
});

UI 버전에서만 작동하기 때문에 거기에 파일 크기 기능을 추가 한 것을 알 수 있습니다.

추가 : @lopsided 제안 과거 문제 얻기 위해 업데이트 data.originalFiles[0]['type'].length하고 data.originalFiles[0]['size'].length있는지가 존재하고 오류를 테스트하기 전에 먼저 비어 있지 않은 확인하기 위해 쿼리를. 존재하지 않으면 오류가 표시되지 않으며 서버 측 오류 테스트에만 의존합니다.


답변

당신은 포함해야한다 jquery.fileupload-process.jsjquery.fileupload – validate.js 이 작동하도록합니다.


답변

이전의 대답에 제안, 우리는 두 개의 추가 파일을 포함 할 필요가 – jquery.fileupload-process.js다음 jquery.fileupload-validate.js그러나 파일을 추가하는 동안 나는 몇 가지 추가 아약스 호출을 수행 할 필요가, 나는이에 가입하고 fileuploadadd이벤트 것은 이러한 호출을 수행 할 수 있습니다. 이러한 사용과 관련하여이 플러그인의 작성자 는 다음을 제안했습니다.

여기를보세요 :
https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options

bind (또는 jQuery 1.7 이상을 사용하는 메서드) 메서드를 통해 추가 이벤트 리스너를 추가하는 것은 jQuery 파일 업로드 UI 버전에서 콜백 설정을 보존하는 데 선호되는 옵션입니다.

또는 https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50 과 같이 자체 콜백에서 간단히 처리를 시작할 수도 있습니다.

두 가지 제안 옵션의 조합을 사용하면 다음 코드가 완벽하게 작동합니다.

$fileInput.fileupload({
    url: 'upload_url',
    type: 'POST',
    dataType: 'json',
    autoUpload: false,
    disableValidation: false,
    maxFileSize: 1024 * 1024,
    messages: {
        maxFileSize: 'File exceeds maximum allowed size of 1MB',
    }
});

$fileInput.on('fileuploadadd', function(evt, data) {
    var $this = $(this);
    var validation = data.process(function () {
        return $this.fileupload('process', data);
    });

    validation.done(function() {
        makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
            .done(function(resp) {
                data.formData = data.formData || {};
                data.formData.someData = resp.SomeData;
                data.submit();
        });
    });
    validation.fail(function(data) {
        console.log('Upload error: ' + data.files[0].error);
    });
});


답변

이것은 firefox에서 나를 위해 작동합니다.

$('#fileupload').fileupload({

    dataType: 'json',
    //acceptFileTypes: /(\.|\/)(xml|pdf)$/i,
    //maxFileSize: 15000000,

    add: function (e, data) {
        var uploadErrors = [];

        var acceptFileTypes = /\/(pdf|xml)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('File type not accepted');
        }

        console.log(data.originalFiles[0]['size']) ;
        if (data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);
            data.submit();
        }

    },
    done: function (e, data) {
        data.context.text('Success!.');
    }
});


답변

“jquery.fileupload-ui.js”라는 파일을 열면 다음과 같은 코드가 표시됩니다.

 $.widget('blueimp.fileupload', $.blueimp.fileupload, {

    options: {
        // By default, files added to the widget are uploaded as soon
        // as the user clicks on the start buttons. To enable automatic
        // uploads, set the following option to true:
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        autoUpload: false,
        // The ID of the upload template:
        uploadTemplateId: 'template-upload',
        // The ID of the download template:
        downloadTemplateId: 'template-download',
        。。。。

다음과 같이 새 속성 “acceptFileTypes”를 한 줄 코드 만 추가하면됩니다.

 options: {
        // By default, files added to the widget are uploaded as soon
        // as the user clicks on the start buttons. To enable automatic
        // uploads, set the following option to true:
        **acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,**
        autoUpload: false,
        // The ID of the upload template:
        uploadTemplateId: 'template-upload',
        // The ID of the download template:
        downloadTemplateId: 'template-d

이제 모든 것이 괜찮다는 것을 알게 될 것입니다! ~ 당신은 단지 잘못된 장소로 속성을 취합니다.


답변

모든 플러그인 JS를 올바른 순서로 가져 왔지만 여전히 문제가있는 경우 고유 한 “add”핸들러를 지정하면 일반적으로 실행되는 * -validate.js 플러그인의 핸들러를 nerfs하는 것 같습니다. data.process ()를 호출하여 모든 유효성 검사를 해제합니다. 따라서이를 수정하려면 “add”이벤트 핸들러에서 다음과 같이하십시오.

$('#whatever').fileupload({
...
add: function(e, data) {
   var $this = $(this);
   data.process(function() {
      return $this.fileupload('process', data);
   }).done(function(){
      //do success stuff
      data.submit(); <-- fire off the upload to the server
   }).fail(function() {
      alert(data.files[0].error);
   });
}
...
});


답변

확인 / 유효한 예 :

  • 여러 파일 입력
  • 하나 또는 여러 파일 업로드- $.grep()오류가있는 배열에서 파일을 제거합니다.
  • imageaudio형식
  • 문자열의 동적 파일 유형 new RegExp()

주의 사항 : acceptFileTypes.test()– 같은 ADIO 파일, 마임 유형을 확인 .mp3이 될 것입니다 audio/mpeg뿐만 아니라 확장 파일 -. 모든 blueimp 옵션 : https://github.com/blueimp/jQuery-File-Upload/wiki/Options

$('input[type="file"]').each(function(i){

    // .form_files is my div/section of form for input file and progressbar
    var $progressbar = $(this).parents('.form_files:first').find('.progress-bar:first');

    var $image_format = 'jpg|jpeg|jpe|png|gif';
    var $audio_format = 'mp3|mpeg';
    var $all_formats = $image_format + '|' + $audio_format;

    var $image_size = 2;
    var $audio_size = 10;
    var mb = 1048576;

    $(this).fileupload({
        // ...
        singleFileUploads: false,   // << send all together, not single
        // ...
        add: function (e, data) {

            // array with all indexes of files with errors
            var error_uploads_indexes = [];

            // when add file - each file
            $.each(data.files, function(index, file) {

                // array for all errors
                var uploadErrors = [];


                // validate all formats first
                if($all_formats){

                    // check all formats first - before size
                    var acceptFileTypes = "(\.|\/)(" + $all_formats + ")$";
                    acceptFileTypes = new RegExp(acceptFileTypes, "i");

                    // when wrong format
                    if(data.files[index]['type'].length && !acceptFileTypes.test(data.files[index]['type'])) {
                        uploadErrors.push('Not an accepted file type');

                    }else{

                        // default size is image_size
                        var $my_size = $image_size;

                            // check audio format
                            var acceptFileTypes = "(\.|\/)(" + $audio_format + ")$";
                            acceptFileTypes = new RegExp(acceptFileTypes, "i");

                            // alert(data.files[index]['type']);
                            // alert(acceptFileTypes.test('audio/mpeg'));

                            // if is audio then size is audio_size
                            if(data.files[index]['type'].length && acceptFileTypes.test(data.files[index]['type'])) {
                                $my_size = $audio_size;
                            }

                        // check size
                        if(data.files[index]['size'] > $my_size * mb) {
                            uploadErrors.push('Filesize is too big');
                        };
                    };

                }; // << all_formats

                // when errors
                if(uploadErrors.length > 0) {
                    //  alert(uploadErrors.join("\n"));

                    // mark index of error file
                    error_uploads_indexes.push(index);
                    // alert error
                    alert(uploadErrors.join("\n"));

                };

            }); // << each


            // remove indexes (files) with error
            data.files = $.grep( data.files, function( n, i ) {
                return $.inArray(i, error_uploads_indexes) ==-1;
            });


            // if are files to upload
            if(data.files.length){
                // upload by ajax
                var jqXHR = data.submit().done(function (result, textStatus, jqXHR) {
                        //...
                     alert('done!') ;
                        // ...
                });
            } // 

        }, // << add
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressbar.css(
                'width',
                progress + '%'
                );
        }
    }); // << file_upload

    //          
}); // << each input file