How to set a size and file type of image upload in React
Asked Answered
I

3

7

I have a "choose file" image as the picture below. What I want to set the limit size and the file type for image upload, .png or .jpg only

enter image description here

My code is below. It looks like when the user chooses .png or .jpg or any file types, it pops up an alert message, and then the image will be approved. I want .png and .jpg works well, but other files chosen displayed an alert message

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;

Can anyone stop by for help? I am really appreciated for that

Inorganic answered 20/10, 2020 at 23:46 Comment(0)
E
3

<Input id="profile-img-file-input" type="file" accept="image/jpeg, image/png" />

1: No need to do any js you can simply pass accept attribute if you want to allow only images then pass "image/*", or if you want only jpeg image then "image/jpeg" same goes for any other image png etc, or if you want to allow only pdf file then pass "application/pdf".

2: And the second one is that you want to add a size limit that's also really easy, an onChange event on the input type file provides you with image files that you've selected in e.target.files(array [file]). if you have only one file selected then simply take its size like this (e.target.files[0].size "it provides the size in bytes and I think 200 kb are around 240000 bytes") then you can simply convert them and do all the size limit logic and show an alert if it exceeds the size limit.

Hope it helps.

Evocator answered 12/3, 2023 at 8:32 Comment(0)
R
0
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;
}

The problem is the logic of the validation if you use an OR statement if one of the conditions is true then it would enter in the if scope. For example if some user uploads a .png this part file != ".png" would be false but the other one file !=".jpg" is true so the condition would turn into true false || true = true.

Ross answered 6/12, 2021 at 0:45 Comment(0)
B
-1

The way I'd solve this is like this (with 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>);

See codesandbox with working code.

btw, returning false inside a React component doesn't do what it seems you expect it to do. It will stop rendering your UI altogether

Bakelite answered 22/10, 2020 at 7:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.