我在rails应用程序中使用jquery-file-upload,我需要防止上传损坏的图像,因为用户试图使用有效的文件扩展名上传损坏的图像文件。
想要使用javascrpt验证客户端,以避免在超过50 MB的大文件的服务器上进行验证的长时间延迟。
我可以检查文件类型,但是如何使用jquery / native javascript / jquery-file-upload可靠地验证非常大的有效和未损坏的jpg或tif图像?
$('form[id*=photo]').fileupload({
dataType: 'script',
pasteZone: null,
sequentialUploads: true,
formData: {fileupload: 'ajax'},
add: function(e, data) {
if($('#photo_id').val() == ""){
data.type = 'POST';
}else{
data.type = 'PUT';
data.url = "/photos/" + $('#photo_id').val();
}
if(this.id != "new_photo"){
data.type = 'PUT';
}
types = /(\.|\/)(jpe?g|tif|tiff)$/i;
file = data.files[0];
if( types.test(file.type) || types.test(file.name) ) {
data.context = $(tmpl("template-upload", file));
$('.upload').remove();
$('#progbar').append(data.context);
$('#control-group-progress').show();
data.submit();
} else {
alert("We're sorry but the file " + file.name + " is not in a supported tiff or jpg image file format. Please select a jpeg (jpg) or tiff file. Thanks!");
}
},
progress: function(e, data) {
if(data.context) {
progress = parseInt(data.loaded / data.total * 100, 10);
progress = parseInt(progress * 0.9, 10);
data.context.find('.bar').css('width', progress + '%');
data.context.find('.progress_percent').html(progress + "%");
}
},
always: function(e, data) {
data.context.find('.bar').css('width', '100%');
data.context.find('.progress_percent').html("100%");
}
});
答案 0 :(得分:4)
您可以尝试使用以下JavaScript代码验证文件类型和文件大小
var uploadedImgType = $('#photo_id').val();
file = data.files[0];
if(uploadedImgType.match(/(?:jpeg|jpg|tif|tiff)$/) && (file.size/1000/1000 < 50)){
(Do your Stuff);
}else{
alert("We're sorry but the file " + file.name + " is not in a supported tiff or jpg image file format. Please select a jpeg (jpg) or tiff file. Thanks!");
}
其中 file.size / 1000/1000&lt; 50 将检查上传文件的大小是否小于50MB。
答案 1 :(得分:0)
试试这个
var getDataUrl = function (blob) {
var defer = $q.defer();
var reader = new FileReader();
reader.onload = function (e) {
defer.resolve(e.target.result);
};
reader.readAsDataURL(blob);
return defer.promise;
};
file = data.files[0];
getDataUrl(file).then(function (dataUrl) {
var uploadedImg = new Image();
uploadedImg.src = dataUrl;
if (uploadedImg.width && uploadedImg.height) {
// image is OK
} else {
// Image is corrupted
}
});