Is there a way to verify if the data_URL is specifically delivering a video or image file? - Utilizing Firebase with Next.js/React

After uploading the image to Firebase, it is returned as a unique data URL format:

https://firebasestorage.googleapis.com/v0/b/app_name/o/posts%2postId?alt=media&token=token

The challenge lies in determining whether the file type is a video or an image since firebase storage does not include the file extension in the URL.

My first approach involved setting up a state for "mediaType" and using useEffect to check the type of file:

const [mediaType, setMediaType] = useState(null);
    
useEffect(() => {
    if (postImage) {
        const storageRef = firebase.storage().ref();
        storageRef.child(postImage).getDownloadURL().then(url => {
            fetch(url)
                .then(res => res.blob())
                .then(blob => {
                    let type = blob.type;
                    if (type.startsWith("image")) {
                        setMediaType("image");
                    } else if (type.startsWith("video")) {
                        setMediaType("video");
                    } else {
                        setMediaType("other");
                        console.log("Unknown file format: " + type);
                    }
                });
        });
    }
}, [postImage]);

My second attempt involved utilizing FileReader to handle the file and determine its type:

  const handleFile = async (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onload = async (e) => {
        const dataURL = e.target.result;
        if (dataURL.startsWith('data:image/')) {
            setMediaType('image');
            setDataUrl(dataURL);
            console.log("Image: " + dataURL);
        } else if (dataURL.startsWith('data:video/')) {
            setMediaType('video');
            setDataUrl(dataURL);
            console.log("Video: " + dataURL);
        } else {
            let response = await fetch(dataURL);
            let type = response.headers.get("Content-Type");
            if (type.startsWith("image")) {
            setMediaType("image");
            setDataUrl(dataURL);
        } else if (type.startsWith("video")) {
            setMediaType("video");
            setDataUrl(dataURL);
        } else {
            setMediaType("other");
            console.log("Unknown file format: " + type);
        }
      }
    }
    reader.readAsDataURL(file);
 }

The rendering logic based on the mediaType:

 <div className="w-full px-3">
   {mediaType === 'image' ? <img className="shadow-md w-full" src={postImage || 'default-image.jpg'} alt="" /> : null}
   {mediaType === 'video' ? <ReactPlayer layout="fill" url={postImage} config={{file:{attributes:{controlsList:'nodownload'}}}} controls onContextMenu={e => e.preventDefault()}/> : null}
   {mediaType === 'other' ? <p>File is not an image or video</p> : null}
 </div>

Answer №1

To enhance the functionality of uploading files to firebase, I recommend incorporating metadata. Here is a guide on how you can do it:

//Add custom metadata such as content type image/jpeg

var newMetadata = {
  cacheControl: 'public,max-age=300',
  contentType: 'image/jpeg'
  .........
  .........
};

Utilize this metadata during the file upload process like so:

storageRef.updateMetadata(newMetadata).......

When accessing the file, retrieve the set metadata to, for example, determine its type:

storageRef.getMetadata().then((metadata) => {
//Perform operations based on the metadata.......
})

Implementing these steps will help optimize your file management system.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having an issue with Expo React Native where the onPress navigation.openDrawer() function is not functioning properly. I appreciate any assistance you can

I've been experiencing difficulty in opening the Drawer by pressing the header button. Despite multiple attempts, I have been unable to resolve the issue. The specific error message I am encountering is as follows: Menu.js:65 Uncaught TypeError: navig ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

Automatically redirect users to a new page using ReactJs/NextJS after a brief delay of 5 seconds

After a customer logs in, I want to show them a welcome page that automatically redirects them to another page after 5 seconds. To achieve this, I initially set the state with a default value of 5 seconds and then used setInterval to count down by 1 every ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

What is the correct way to import React's experimental hooks?

I am eager to explore the cutting-edge and unreleased features of React, particularly the "useEffectEvent" hook. However, I have encountered a problem while trying to import this specific feature from the React package. Whenever I attempt to import somet ...

Sorry, but you can only use one 'in' filter in your query

this.ref.collection("users", ref => ref.where("uid1","in", [reciverId, senderId]) .where("uid2","in", [reciverId, senderId])) throws an error stating: "Invalid query. Multiple 'in' filters cannot be used." ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

Tips for updating the appearance of material-ui table pagination

I'm looking to enhance the way table pagination is presented in material-ui. The current default display by material-ui looks like this: https://i.stack.imgur.com/d4k4l.png My goal is to modify it to look more like this: https://i.stack.imgur.com/A ...

Issue with Material UI textfield: Unable to enter input or set values on a controlled component

I recently attempted to develop a customized input component using the inputRef feature in Material UI's Input component. Although I successfully implemented the component reference, I encountered an issue where I could not enter any values into the t ...

Encountering an error with Dynamic Control generic react-hook-form: Error code TS2322 appears - Type 'Control<FormFields, any>' cannot be assigned to type 'Control<FieldValues, any>'

Within my application, I am utilizing react-hook-form in conjunction with the latest version of MUI 5.11. I have developed a reusable Select component: ...someImports import { Control, Controller } from 'react-hook-form'; interface SelectProps { ...

What is the best way to apply a unique style (such as adding a bottom border) to all list items

Currently, I am utilizing React Material components with a List that is internally represented as ul li elements. My goal is to apply a style to all li elements by adding a bottom border. One approach is to include the className={classes.sideBar__listItem_ ...

Yarn encountered an exit code of 1 and failed to create the app during the command execution

I've been working on creating a next.js app with tailwindcss, but I keep encountering an error when using the following command: yarn create next-app -e -tailwindcss demo-app-full Every time I run this command, it gives me the following error message ...

Coat the div with a uniform shade of pure white

I need assistance on applying a solid white background color to hide the text behind it. For better understanding, I have attached a screenshot as a reference. https://i.stack.imgur.com/f8Qd9.png The issue arises when I click on the dropdown in the heade ...

I am unable to access or retrieve video content from my MongoDB database to display on my user interface

I am having trouble retrieving video or fetching video from my MongoDB to display on the UI frontend where I have stored videos in an array. I would appreciate any suggestions. I've tried everything I could think of. Currently, I am only able to retr ...

implementing GraphQL lists in mutations using Apollo in a React JS application

My current situation involves a mutation that looks like this: orderAdd(products: [ProductInput],restaurant: RestaurantInput) implemented in graphql, and now I want to pass parameters to it using Apollo in react js as shown below: mutation orderAdd ($ ...

Developing NextJS 13 with App directory integration for socket.io

How do I initialize a socket in the app/api/socket/route.js directory? When referencing the example in the pages/api/socket.js directory, it seems that it does not return an instance of http.ServerResponse. Instead, it returns NextResponse, which does not ...

Getting the ID of an element in ReactJS following a POST request

I am looking to implement a function that creates an entry in a database using data collected from a basic form. Once the user clicks on submit, this function is triggered: createItem(item){ this.state.bucket_list.push({ name: item, ...

Should the JSON data in an ASP.NET React application be serialized and normalized on the client-side or server-side?

Currently, I am in the process of developing a asp.net react application. Up until now, I have successfully completed the serialization and normalization of nested data on the client-side using normalizr. However, I am considering whether it would be more ...