Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.0 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 {
      // Use Promise.all for concurrent processing of files
      await Promise.all(files.map(async (file, index) => {
        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 reader = new FileReader();
        reader.onload = () => {
          const imageData = JSON.parse(localStorage.getItem('Images')) || [];
          imageData.push({ dataURL: reader.result });
          localStorage.setItem('Images', JSON.stringify(imageData));
        };

        reader.readAsDataURL(compressedImage);
        setFileCount(index + 1);
      }));

    } catch (err) {
      console.error(err);
    }
  };

  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