我只需要通过<input type="file">标签上传图像文件。

现在,它接受所有的文件类型。但是,我想将其限制为特定的图像文件扩展名,包括.jpg, .gif等。

如何实现这个功能?


当前回答

简单而强大的方式(动态接受)

将格式放在数组中,如"image/*"

var上传“上传”= document . getElementById (); var阵列= [/ mp4视频”,“image / p”); 上传. accept =阵列; 上传addEventListener(“change”()= > ' 上传游戏机。log (value)。 ') <输入类型=“文件”id=“上传”>

其他回答

使用type="file"和accept="image/*"(或者你想要的格式),允许用户选择一个特定格式的文件。但是你必须在客户端重新检查,因为用户可以选择其他类型的文件。 这对我很有用。

<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />

然后,在javascript脚本中

processFile(imageInput) {
    if (imageInput.files[0]) {
      const file: File = imageInput.files[0];
      var pattern = /image-*/;

      if (!file.type.match(pattern)) {
        alert('Invalid format');
        return;
      }

      // here you can do whatever you want with your image. Now you are sure that it is an image
    }
  }

如果你想一次上传多张图片,你可以添加多个属性输入。

上传多个文件:<input type="file" multiple accept='image/*'>

其他人的答案为ReactJS重构(hooks)

import React from 'react';

const ImageUploader = () => {

    const handleImageUpload = (e) => {
        // If no file selected, return
        if (e.target.files.length === 0) return false;
        const file = e.target.files[0];

        // If no image selected, return
        if (!/^image\//.test(file.type)) {
            alert(`File ${file.name} is not an image.`);
            return false;
        }

        // ...
    };

    return (
        <>
            <input type='file' accept='image/*' onChange={(e) => handleImageUpload(e)} />
        </>
    );
};

export default ImageUploader;

像这样使用它

<input type="file" accept=".png, .jpg, .jpeg" />

这对我很有效

https://jsfiddle.net/ermagrawal/5u4ftp3k/

步骤: 1. 为输入标签添加接受属性 2. 使用javascript验证 3.添加服务器端验证,以验证内容是否确实是预期的文件类型

对于HTML和javascript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }   
    }
</script>
</body>
</html>

解释:

属性中显示的文件进行筛选 弹出文件选择器。然而,它不是一个验证。这只是一个 浏览器提示。中的选项,用户仍然可以更改 弹出。 javascript只验证文件扩展名,但不能 真正验证所选文件是真正的JPG还是png。 因此,您必须在服务器端编写文件内容验证。