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

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

如何实现这个功能?


当前回答

像这样使用它

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

这对我很有效

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

其他回答

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

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

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

用这个:

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

工作在FF和Chrome。

使用输入标记的accept属性。要只接受PNG, JPEG和GIF,您可以使用以下代码:

<标签>你的形象文件 <输入类型=“文件” < - >标签

或者仅仅是:

<标签>你的形象文件 <输入类型=“文件” < - >标签

请注意,这只向浏览器提供了一个提示,提示要向用户显示什么文件类型,但这很容易避免,因此您也应该始终在服务器上验证上传的文件。

它应该可以在IE 10+, Chrome, Firefox, Safari 6+, Opera 15+上运行,但在手机上的支持非常粗略(截至2015年),根据一些报告,这实际上可能会阻止一些移动浏览器上传任何东西,所以一定要好好测试你的目标平台。

有关浏览器支持的详细信息,请参见http://caniuse.com/#feat=input-file-accept

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

<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')
    }
  }