如何在客户端(Javascript)验证文件输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10133437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:48:11  来源:igfitidea点击:

How to validate a file input on client side (Javascript)

javascriptjqueryvalidation

提问by user1324106

I have a form stored in a javascript variable below:

我有一个存储在下面的 javascript 变量中的表单:

var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >" + 
"<label> Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label></form>

Now as you can see when the user clicks on the submit button, it submits to the 'startImageUpload' function which is below:

现在你可以看到当用户点击提交按钮时,它提交到下面的“startImageUpload”函数:

function startImageUpload(imageuploadform){
  $(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
  $(imageuploadform).find('.imagef1_upload_form').css('visibility','hidden');
  sourceImageForm = imageuploadform;
      return true;
}

What it does is that when the user clicks on submit, it displays a loading bar and uploads the form.

它的作用是当用户点击提交时,它会显示一个加载栏并上传表单。

Now what my question is that I want to perform a simple javascript validation where when the user clicks on the submit button in the form, it will check if the file either a 'png' or 'gif' file type. If it is correct file type, then display the loading bar and upload the form. If the file type is incorrect, then show a n alert stating file type is incorrect but don't show the loading bar and do not upload the form.

现在我的问题是我想执行一个简单的 javascript 验证,当用户单击表单中的提交按钮时,它会检查文件是“png”还是“gif”文件类型。如果文件类型正确,则显示加载栏并上传表单。如果文件类型不正确,则显示一个警告,说明文件类型不正确,但不显示加载栏并且不上传表单。

Does anyone know how this can be coded. It is so I can use the example from one of your answers to then expand on it and use the javascript to validate on more file types and also file size so it will be very helpful if somebody can please help me.

有谁知道如何编码。这样我就可以使用您的答案之一中的示例,然后对其进行扩展,并使用 javascript 来验证更多文件类型和文件大小,因此如果有人可以帮助我,这将非常有帮助。

Thank You

谢谢

采纳答案by coder

Try this:

试试这个:

 $("#pic").change(function() {

    var val = $(this).val();

    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png':
            alert("an image");
            break;
        default:
            $(this).val('');
            // error message here
            alert("not an image");
            break;
    }
});

回答by alex

You can check like so...

你可以这样检查...

var validExtensions = ['png', 'gif'],
    validExtensionSupplied = $.inArray(
           ($('.fileImage').val().match(/\.(.*?)]\s*$/) || [])[1],
           validExtensions) != -1;

Alternatively, you can validate by MIME type by checking the $('.fileImage').prop('files')[0].type.

或者,您可以通过检查$('.fileImage').prop('files')[0].type.

回答by Ricardo Tomasi

function startImageUpload(imageuploadform){

  var form = $(imageuploadform)
    , value = form.find('.fileImage').val()

  form.find('.imagef1_upload_process').css('visibility','visible')
  form.find('.imagef1_upload_form').css('visibility','hidden')

  if (!/\.(png|gif)$/.test(value)){
    return false
  }
  return true
}

The HTML specification also evolved to include an acceptattribute:

HTML 规范还演变为包括一个accept属性:

<input type="file" accept="image/png,image/gif" />

(supported in Chrome, Firefox and Opera - IE10, Safari 6 in the near future)

(在不久的将来支持 Chrome、Firefox 和 Opera - IE10、Safari 6)

回答by Dennys Marquez

This is my Solution, it is quite Easy and Fast

这是我的解决方案,非常简单快捷

    var accept = $(event.target).attr('accept');
    //<input name='fileImage' accept='.png,.jpg,.jpeg' type='file'  class='fileImage' />

    value = $(event.target).val(), ext = value.substring(value.lastIndexOf('.'));

    if(ext && accept.indexOf(ext) == -1){

        console.log('No');

    }