Skip to content

Commit

Permalink
ImageUploader should work better now
Browse files Browse the repository at this point in the history
  • Loading branch information
luloxi committed Sep 28, 2024
1 parent 2a31dc0 commit 2e7482b
Showing 1 changed file with 14 additions and 24 deletions.
38 changes: 14 additions & 24 deletions packages/nextjs/app/create/_components/ImageUploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import React, { useState } from "react";
import Image from "next/image";
import imageCompression from "browser-image-compression";
import { notification } from "~~/utils/scaffold-eth";
import { addToIPFS } from "~~/utils/simpleNFT/ipfs-fetch";

Expand All @@ -19,34 +18,25 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({ image, setUploaded

// Handle file drop or selection
const handleFileUpload = async (file: File) => {
try {
setLoading(true);

// Compress the image
const options = {
maxSizeMB: 0.2, // Maximum size in MB
maxWidthOrHeight: 1920, // Maximum width or height
useWebWorker: false, // Use web worker for faster compression
};
const compressedFile = await imageCompression(file, options);

// Upload the compressed file to IPFS
const ipfsPath = await addToIPFS(compressedFile);
setUploadedImageIpfsPath(ipfsPath);
// Read the file and set preview
const reader = new FileReader();
reader.onloadend = () => setPreviewImage(reader.result as string); // Show preview
reader.readAsDataURL(file); // Convert image to base64 for preview

// Update the preview image
const reader = new FileReader();
reader.onloadend = () => {
setPreviewImage(reader.result as string);
};
reader.readAsDataURL(compressedFile);
// Upload file to IPFS
setLoading(true);
const notificationId = notification.loading("Uploading image to IPFS...");

notification.success("Image uploaded successfully!");
try {
const uploadedImage = await addToIPFS(file, true); // Upload image to IPFS
notification.success("Image uploaded to IPFS!");
setUploadedImageIpfsPath(uploadedImage.path); // Store IPFS path for later use
setLoading(false);
notification.remove(notificationId);
} catch (error) {
console.error("Failed to upload image to IPFS:", error);
notification.error("Failed to upload image to IPFS.");
} finally {
setLoading(false);
notification.remove(notificationId);
}
};

Expand Down

0 comments on commit 2e7482b

Please sign in to comment.