Suvojit Ray
Suvojit Ray

Reputation: 41

How to check that an ipfs hash is an image/video/.. in React Js?

I need to use the ipfs hash to find out whether the file is an image or a video so that i can use it to either show the image/play the video. Couldn't find any useful resource on this one. What should be done?

Upvotes: 4

Views: 474

Answers (2)

SHUBHAM SINGH
SHUBHAM SINGH

Reputation: 377

This code will check first image load if error while loading image then it will try to load video if video loading also failed then it will add a sample dummy image only

 import { Fragment, useState } from "react";
    import noImagePreview from "../../Assets/Images/noImage.png"
    
    const ImageComponent = (props) => {
        const [imageLoadFailed, setImageLoadFailed] = useState(false)
        const [videoLoadFailed, setVideoLoadFailed] = useState(false)
        return (
            <Fragment>
                {!imageLoadFailed && !videoLoadFailed &&
                    <img {...props} alt={props?.alt}
                        onError={({ currentTarget }) => {
                            currentTarget.onerror = null; // prevents looping
                            currentTarget.src = noImagePreview;
                            setImageLoadFailed(true)
                        }} />
                }
    
                {/* If image not loaded then load the video  */}
                {imageLoadFailed && !videoLoadFailed &&
                    <video width="100%" height="100%" autoPlay muted
                        onError={() => setVideoLoadFailed(true)}>
                        <source src={props?.src} type="video/mp4" />
                    </video>
                }
    
                {videoLoadFailed &&
                    <img {...props} alt={props?.alt}
                        onError={({ currentTarget }) => {
                            currentTarget.onerror = null; // prevents looping
                            currentTarget.src = noImagePreview;
                        }} />
                }
            </Fragment>
    
        )
    }
    
    export default ImageComponent

Upvotes: 0

notnavindu
notnavindu

Reputation: 507

You can't find it just by using the ipfs hash. You're gonna have to fetch the file and find the mime type of it. Check out these threads 1 2

Upvotes: 1

Related Questions