1

我在 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%");
  }
}); 
4

2 回答 2

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 < 50将检查上传文件的大小是否小于 50MB。

于 2014-03-13T07:31:44.120 回答
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
      }
    });
于 2015-06-09T13:34:30.800 回答