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

qoefvg9y  于 2023-01-30  发布在  React
关注(0)|答案(2)|浏览(335)

我有一个“选择文件”的图像作为下面的图片。我想设置的限制大小和文件类型的图像上传,.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;

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

pdsfdshx

pdsfdshx1#

const fileExtension = file.name.split(".").at(-1);
const allowedFileTypes = ["jpg", "png"];
if (!allowedFileTypes.includes(fileExtension)) {
    window.alert(`File does not support. Files type must be ${allowedFileTypes.join(", ")}`);
    return false;
}

问题在于验证的逻辑,如果使用OR语句,如果其中一个条件为真,则它将进入if范围。例如,如果某个用户上载.png,则此部分file!=“.png”将为假,但另一部分file!=".jpg”为真,因此条件将变为真假||真=真

eyh26e7m

eyh26e7m2#

我解决这个问题的方法如下(使用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>);

请参见code工作时的代码和框。
顺便说一句,在React组件中返回false并不会像您期望的那样,它将完全停止呈现您的UI

相关问题