blueimp 파일 업로드 플러그인의 maxFileSize 및 acceptFileTypes가 작동하지 않습니다. 왜?
업로드 파일에 Blueimp jQuery 파일 업로드 플러그인을 사용하고 있습니다.
나는 업로드하지만 옵션에는 문제가 없었다 maxFileSize
및 acceptFileTypes
작업을하지 않습니다.
이것은 내 코드입니다.
$(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.js 및 jquery.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()
오류가있는 배열에서 파일을 제거합니다. image
및audio
형식- 문자열의 동적 파일 유형
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
Add 이벤트에 대한 이벤트 핸들러의 예입니다. singleFileUploads 옵션이 활성화되어 있다고 가정합니다 (기본값). add / fileuploadadd 이벤트를 바인딩하는 방법에 대한 jQuery 파일 업로드 문서를 더 읽어보세요. 내부 루프는 vars this 또는 file 모두 사용할 수 있습니다 . size 속성을 가져 오는 예 : this [ 'size'] 또는 file.size .
/**
* Handles Add event
*/
base.eventAdd = function(e, data) {
var errs = [];
var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i;
var maxFileSize = 5000000;
// Validate file
$.each(data.files, function(index, file) {
if (file.type.length && !acceptFileTypes.test(file.type)) {
errs.push('Selected file "' + file.name + '" is not alloawed. Invalid file type.');
}
if (this['size'] > maxFileSize) {
errs.push('Selected file "' + file.name + '" is too big, ' + parseInt(file.size / 1024 / 1024) + 'M.. File should be smaller than ' + parseInt(maxFileSize / 1024 / 1024) + 'M.');
}
});
// Output errors or submit data
if (errs.length > 0) {
alert('An error occured. ' + errs.join(" "));
} else {
data.submit();
}
};
이것은 크롬에서 나를 위해 일했으며 jquery.fileupload.js 버전은 5.42.3입니다.
add: function(e, data) {
var uploadErrors = [];
var ext = data.originalFiles[0].name.split('.').pop().toLowerCase();
if($.inArray(ext, ['odt','docx']) == -1) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0].size > (2*1024*1024)) {//2 MB
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
.fileupload({
add: function (e, data) {
var attachmentValue = 3 * 1000 * 1024;
var totalNoOfFiles = data.originalFiles.length;
for (i = 0; i < data.originalFiles.length; i++) {
if (data.originalFiles[i]['size'] > attachmentValue) {
$attachmentsList.find('.uploading').remove();
$attachmentMessage.append("<li>" + 'Uploaded bytes exceeded the file size' + "</li>");
$attachmentMessage.show().fadeOut(10000, function () {
$attachmentMessage.html('');
});
data.originalFiles.splice(i, 1);
}
}
if (data.files[0]) {
$attachmentsList
.prepend('<li class="uploading" class="clearfix loading-content">' + data.files[0].name + '</li>');
}
data.submit();
}
다음과 같은 추가 기능을 사용할 수도 있습니다.
function checkFileType(filename, typeRegEx) {
if (filename.length < 4 || typeRegEx.length < 1) return false;
var filenameParts = filename.split('.');
if (filenameParts.length < 2) return false;
var fileExtension = filenameParts[filenameParts.length - 1];
return typeRegEx.test('.' + fileExtension);
}
당신은 포함해야한다 jquery.fileupload-process.js 및 jquery.fileupload - validate.js 이 작동하도록합니다.
그때...
$(this).fileupload({
// ...
processfail: function (e, data) {
data.files.forEach(function(file){
if (file.error) {
self.$errorMessage.html(file.error);
return false;
}
});
},
//...
}
processfail 콜백은 유효성 검사가 실패한 후 시작됩니다.
- 파일 확장자를 사용하여 파일 유형을 확인할 수도 있습니다.
더 간단한 방법은 다음과 같이 add 내부에 주어진 것과 같이하는 것입니다.
add : function (e,data){ var extension = data.originalFiles[0].name.substr( (data.originalFiles[0].name.lastIndexOf('.') +1) ); switch(extension){ case 'csv': case 'xls': case 'xlsx': data.url = <Your URL>; data.submit(); break; default: alert("File type not accepted"); break; } }
여러 파일이있는 경우 루프를 사용하여 각 파일 형식을 확인합니다.
add: function(e, data) {
data.url = 'xx/';
var uploadErrors = [];
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
console.log(data.originalFiles);
for (var i = 0; i < data.originalFiles.length; i++) {
if(data.originalFiles[i]['type'].length && !acceptFileTypes.test(data.originalFiles[i]['type'])) {
uploadErrors.push('Not an accepted file type');
data.originalFiles
}
if(data.originalFiles[i]['size'].length && data.originalFiles[i]['size'] > 5000000) {
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
}
}
data.submit();
},
서버에서 일반적으로 지원되는 형식을 찾는 경우
3g2|3gp|3gp2|3gpp|aac|aaf|aca|accdb|accde|accdt|acx|adt|adts|afm|ai|aif|aifc|aiff|appcache|application|art|asd|asf|asi|asm|asr|asx|atom|au|avi|axs|bas|bcpio|bin|bmp|c|cab|calx|cat|cdf|chm|class|clp|cmx|cnf|cod|cpio|cpp|crd|crl|crt|csh|css|csv|cur|dcr|deploy|der|dib|dir|disco|dll|dllconfig|dlm|doc|docm|docx|dot|dotm|dotx|dsp|dtd|dvi|dvr-ms|dwf|dwp|dxr|eml|emz|eot|eps|esd|etx|evy|exe|execonfig|fdf|fif|fla|flr|flv|gif|gtar|gz|h|hdf|hdml|hhc|hhk|hhp|hlp|hqx|hta|htc|htm|html|htt|hxt|ico|ics|ief|iii|inf|ins|isp|IVF|jar|java|jck|jcz|jfif|jpb|jpe|jpeg|jpg|js|json|jsonld|jsx|latex|less|lit|lpk|lsf|lsx|lzh|m13|m14|m1v|m2ts|m3u|m4a|m4v|man|manifest|map|mdb|mdp|me|mht|mhtml|mid|midi|mix|mmf|mno|mny|mov|movie|mp2|mp3|mp4|mp4v|mpa|mpe|mpeg|mpg|mpp|mpv2|ms|msi|mso|mvb|mvc|nc|nsc|nws|ocx|oda|odc|ods|oga|ogg|ogv|one|onea|onepkg|onetmp|onetoc|onetoc2|osdx|otf|p10|p12|p7b|p7c|p7m|p7r|p7s|pbm|pcx|pcz|pdf|pfb|pfm|pfx|pgm|pko|pma|pmc|pml|pmr|pmw|png|pnm|pnz|pot|potm|potx|ppam|ppm|pps|ppsm|ppsx|ppt|pptm|pptx|prf|prm|prx|ps|psd|psm|psp|pub|qt|qtl|qxd|ra|ram|rar|ras|rf|rgb|rm|rmi|roff|rpm|rtf|rtx|scd|sct|sea|setpay|setreg|sgml|sh|shar|sit|sldm|sldx|smd|smi|smx|smz|snd|snp|spc|spl|spx|src|ssm|sst|stl|sv4cpio|sv4crc|svg|svgz|swf|t|tar|tcl|tex|texi|texinfo|tgz|thmx|thn|tif|tiff|toc|tr|trm|ts|tsv|ttf|tts|txt|u32|uls|ustar|vbs|vcf|vcs|vdx|vml|vsd|vss|vst|vsto|vsw|vsx|vtx|wav|wax|wbmp|wcm|wdb|webm|wks|wm|wma|wmd|wmf|wml|wmlc|wmls|wmlsc|wmp|wmv|wmx|wmz|woff|woff2|wps|wri|wrl|wrz|wsdl|wtv|wvx|x|xaf|xaml|xap|xbap|xbm|xdr|xht|xhtml|xla|xlam|xlc|xlm|xls|xlsb|xlsm|xlsx|xlt|xltm|xltx|xlw|xml|xof|xpm|xps|xsd|xsf|xsl|xslt|xsn|xtp|xwd|z|zip
'development' 카테고리의 다른 글
const에 대한 포인터 삭제 (T const *) (0) | 2020.09.24 |
---|---|
사용자가 "로그인"되었는지 확인하는 방법은 무엇입니까? (0) | 2020.09.23 |
이러한 파일을로드 할 수 없습니다 — sqlite3 / sqlite3_native (LoadError) on ruby on rails (0) | 2020.09.23 |
사용자 정의 std :: set 비교기 사용 (0) | 2020.09.23 |
GridView가 양식 태그 내에 있더라도 runat =“server”인 양식 태그 내에 GridView를 배치해야합니다. (0) | 2020.09.23 |