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

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

如何实现这个功能?


当前回答

用这个:

<input type="file" accept="image/*">

工作在FF和Chrome。

其他回答

用这个:

<input type="file" accept="image/*">

工作在FF和Chrome。

在html中;

<input type="file" accept="image/*">

这将接受所有的图像格式,但不接受其他文件,如pdf或视频。

但是如果你使用的是django, django forms.py;

image_field = forms.ImageField(Here_are_the_parameters)

只是作为一个补充:如果你想包括所有的现代图像文件类型与最好的跨浏览器支持,它应该是:

<input type="file" accept="image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp">

这允许在大多数浏览器中显示的所有图像文件类型,同时排除不太常见的格式,如TIFF或不适合web的格式,如PSD。

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

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

使用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
    }
  }