如何在React中设置图片上传的大小和文件类型

Sun*_*nny 6 alert file-upload image reactjs

我有一个“选择文件”图像,如下图所示。我想设置图像上传的限制大小和文件类型,仅限 .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;
Run Code Online (Sandbox Code Playgroud)

有人可以过来寻求帮助吗?我真的很感激

poe*_*eek -1

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

import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import UploadPreview from "@rpldy/upload-preview";

const filterBySize = (file) => {
    return file.size <= 1e+7;
};
    
const App = () => (<Uploady
       destination={{ url: "my-server.com/upload" }}
       fileFilter={filterBySize}
       accept=".png,.jpg,.jpeg"
    >
       <UploadButton/>
       <UploadPreview/>
</Uploady>);
Run Code Online (Sandbox Code Playgroud)

请参阅包含工作代码的codesandbox 。

顺便说一句,在 React 组件中返回 false 并不会执行您期望的操作。它将完全停止渲染你的 UI