Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.3 kB
1
Indexable
Never
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import imageCompression from 'browser-image-compression';

const Dashboard = () => {
  const navi = useNavigate();
  const [fileCount, setFileCount] = useState(0);

  const handleFileChange = async (e) => {
    const files = e.target.files;
    const options = {
      maxSizeMB: 2,
      useWebWorker: true,
    };

    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // Process images asynchronously using a Promise
        await processImage(file, options, i);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const processImage = async (file, options, index) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = async () => {
        try {
          let compressedImage;

          if (file.size > options.maxSizeMB * 1024 * 1024) {
            compressedImage = await imageCompression(file, options);
          } else {
            compressedImage = file;
          }

          console.log('file size before compress:', file.size);
          console.log('file size after compress:', compressedImage.size);

          const imageData = JSON.parse(localStorage.getItem('Images')) || [];
          imageData.push({ dataURL: reader.result });
          localStorage.setItem('Images', JSON.stringify(imageData));

          setFileCount(index + 1);
          resolve();
        } catch (error) {
          console.error(error);
          resolve();
        }
      };

      reader.readAsDataURL(file);
    });
  };

  return (
    <>
      <header>
        <nav>
          <div className="nav-left">
            <h1>Sample App</h1>
          </div>
          <div className="nav-right">
            <p>Welcome !!!!! {localStorage.getItem("name")}</p>
            <Link to="/Dashboard">Dashboard</Link><br/>
            <input type="file" onChange={handleFileChange} multiple />
            <br/><br/>
            <Link to="/FetchImage">Images</Link>
          </div>
        </nav>
      </header>

      <br/>
      <br/>
      
      <button onClick={() => navi('/Weatherdata')}>Weather Search</button>
    </>
  );
};

export default Dashboard;
Leave a Comment