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

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

如何实现这个功能?


当前回答

在html中;

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

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

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

image_field = forms.ImageField(Here_are_the_parameters)

其他回答

使用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" accept=".png, .jpg, .jpeg" />

这对我很有效

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

你可以添加特定类型的图像或其他文件类型,并在你的代码中进行验证:

<input  style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf"
                (change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">
    


  
      handleFileInput(event) {
    console.log(event);
    const file = event.target.files[0];
    if (file.size > 2097152) {
        throw err;
    } else if (
      file.type !== "application/pdf"  &&
      file.type !== "application/wps-office.pdf"   && 
      file.type !== 'application/pdf'  && file.type !== 'image/jpg'  && file.type !== 'image/jpeg'  && file.type !== "image/png"
    ) {
throw err;
    } else {
      
        console.log('file valid')
    }
  }

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

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

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

你可以使用accept属性<input type="file">读取这个文档http://www.w3schools.com/tags/att_input_accept.asp