Skip to content

Commit

Permalink
Created a module for Image upload (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jikugodwill authored Jul 17, 2024
1 parent 1ed8af2 commit da39c66
Showing 1 changed file with 104 additions and 0 deletions.
104 changes: 104 additions & 0 deletions widget/IpfsImageUpload.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const IPFSImageUpload = ({
key,
name,
className,
img,
setImg,
msg,
setMsg,
onError,
accepts,
multiple,
clickable,
maxFiles,
maxFileSize,
minFileSize,
dragActiveClassName,
}) => {
const attributes = {
key,
name,
className,
img,
setImg,
msg,
setMsg,
onError,
accepts,
multiple,
clickable,
maxFiles,
maxFileSize,
minFileSize,
dragActiveClassName,
};
const ipfsUrl = (cid) => `https://ipfs.near.social/ipfs/${cid}`;
const uploadFile = (files) => {
setMsg("Uploading...");

const file = files[0];

const uploadPromise = asyncFetch("https://ipfs.near.social/add", {
method: "POST",
headers: {
"Content-Type": file.type,
},
body: file,
})
.then((response) => {
if (!response.ok) {
setMsg("Upload failed!");
return Promise.reject(new Error("Upload failed"));
}
return response.body;
})
.then((data) => {
console.log(data);
setImg(data);
})
.catch((error) => {
console.error("Upload error:", error);
setMsg("Upload failed!");
})
.finally(() => {
setMsg("Replace Image");
});

uploadPromise
.then(() => {
console.log("Upload successful!");
})
.catch((error) => {
console.error("Upload failed:", error);
});
};
return (
<div className="d-inline-block" key={attributes.key}>
{img?.cid && (
<div
className="d-inline-block me-2 overflow-hidden align-middle"
style={{ width: "2.5em", height: "2.5em" }}
>
<img
className="rounded w-100 h-100"
style={{ objectFit: "cover" }}
src={ipfsUrl(img?.cid)}
alt="upload preview"
/>
</div>
)}
<Files
multiple={false}
accepts={["image/*"]}
minFileSize={1}
clickable
onChange={uploadFile}
{...attributes}
>
{msg}
</Files>
</div>
);
};

return { IPFSImageUpload };

0 comments on commit da39c66

Please sign in to comment.