Reactjs 如何在React中设置图像上载的大小和文件类型

Reactjs 如何在React中设置图像上载的大小和文件类型,reactjs,image,file-upload,alert,Reactjs,Image,File Upload,Alert,我有一个“选择文件”图像,如下图所示。我想为图像上传设置限制大小和文件类型,仅限.png或.jpg 我的代码如下。看起来,当用户选择.png或.jpg或任何文件类型时,会弹出一条警告消息,然后图像将被批准。我希望.png和.jpg运行良好,但选择的其他文件显示了一条警告消息 import React, {Component, useState} from 'react'; import axios from 'axios'; const Modeling = () => { con

我有一个“选择文件”图像,如下图所示。我想为图像上传设置限制大小和文件类型,仅限.png或.jpg

我的代码如下。看起来,当用户选择.png或.jpg或任何文件类型时,会弹出一条警告消息,然后图像将被批准。我希望.png和.jpg运行良好,但选择的其他文件显示了一条警告消息

import React, {Component, useState} from 'react';
import axios from 'axios';

const Modeling = () => {
  const [file, setFile] = useState(null);

  const fileChangedHandler = event => {
    let file = event.target.files[0];
    let reader = new FileReader();

    console.log(file);
    reader.onload = function(e) {
      setFile(e.target.result);
    };
    reader.readAsDataURL(event.target.files[0]);
 
 if (file != ".png" || file !=".jpg" ) {
      window.alert("File does not support. You must use .png or .jpg ");
      return false;
   }
   if (file.size > 10e6) {
     window.alert("Please upload a file smaller than 10 MB");
     return false;
   }
  };

    return (
      <div id="modeling">
        <div className="container">
          <div className="row">
            <div className="col-xs-12 col-md-8"> 
              <div className="modeling-text">
                <h2>3D MODELING</h2>
                <h3>Upload a 2D image to get a 3D model</h3>        
                
                <input className="btn btn-secondary" 
                      id="fileInput" 
                      name="file" type="file" 
                      inputProps={{ accept: 'image/*' }}
                      onChange={fileChangedHandler} 
                />
             
                <button className="btn btn-primary" style={{float:"left", marginLeft: "10px", marginBottom: "10px"}} 
                        id="renderButton">
                  Render 3D Model
                </button>

              </div>
            </div>
          </div>
          <img src={file} alt={""} width="400" height="400" text-align="left" style={{display:'block'}} />
        </div>
      </div>
    )
  }


export default Modeling;
import React,{Component,useState}来自'React';
从“axios”导入axios;
常量建模=()=>{
const[file,setFile]=useState(null);
const fileChangedHandler=事件=>{
让file=event.target.files[0];
let reader=new FileReader();
console.log(文件);
reader.onload=函数(e){
setFile(e.target.result);
};
reader.readAsDataURL(event.target.files[0]);
如果(文件!=“.png”| |文件!=“.jpg”){
alert(“文件不支持。您必须使用.png或.jpg”);
返回false;
}
如果(file.size>10e6){
window.alert(“请上传小于10MB的文件”);
返回false;
}
};
返回(
三维建模
上载二维图像以获取三维模型
渲染三维模型
)
}
导出默认模型;

有人能过来帮忙吗?我真的很感激

我解决这个问题的方法是这样的(使用):

从“React”导入React;
从“@rpldy/Uploady”导入上传;
从“@rpldy/upload button”导入上载按钮;
从“@rpldy/upload preview”导入UploadPreview;
const filterBySize=(文件)=>{
返回文件大小(
);