website-logomedCode

Next.js 14: How to Add Upload Image from Local Directory

We will explore how to implement image uploading functionality from a local directory into a Next.js application.
MOHAMMED DAKIR| September 18, 2024
next.js
Next.js 14: How to Add Upload Image from Local Directory

#Dev #next.js #upload_image #javascript

 In this article, we will explore how to integrate image uploading functionality from a local directory into a Next.js application. Uploading images is a common requirement in web development, especially when building content-rich platforms like blogs, portfolios, or e-commerce websites. Next.js provides a smooth way to handle this, leveraging its API routes and powerful file-handling capabilities. In this step-by-step guide, we will cover everything from creating the upload form to processing and storing the image files.

Why Image Uploading in Next.js Matters

Adding image uploading functionality in Next.js enhances user experience and brings dynamism to the app. Whether you're developing a blog, an e-commerce site, or a personal portfolio, the ability to upload and display images efficiently is crucial. Next.js's server-side features provide a seamless way to manage image uploads, ensuring faster processing times and smooth rendering for end-users.

Step 1: Setting Up the Project

To begin, ensure you have a Next.js project set up. If you don't have one yet, you can create a new project by running the following commands in your terminal:

npx create-next-app@latest my-image-upload-app

This will scaffold a new Next.js project. We are now ready to add the necessary components for image uploading.

Step 2: Create the Upload Component

We need to create a simple form where users can upload images from their local directory. In Next.js, this can be done easily using a React component. Open your pages/index.js file and add the following code:

import { useState } from 'react';

export default function Home() {
  const [dataUrl, setDataUrl] = useState("");

  const handleFileChange = (event) => {
    setDataUrl(event.target.files[0]);
  };
return ( <div> <h1>Upload an Image</h1> <input type="file" accept="image/*" onChange={handleFileChange} /> <button type="submit">Upload</button> </div> ); }

Step 3: Add Function to get Image Url from Input


import { useState } from 'react';

export default function Home() {
  const [dataUrl, setDataUrl] = useState("");

  const handleFileChange = (event) => {
    setDataUrl(event.target.files[0]);
  };
  const getImageUrl=(event)=>{
    constinput=event.target;
    if (input.files&&input.files[0]) {
      constreader=newFileReader();
      reader.onload= () => {
        constavatarImg=newImage();
        constsrc=reader.result;
        setDataUrl(src);
        avatarImg.onload= () => {
          constcanvas=canvasRef.current;
          constctx=canvas.getContext("2d");
          ctx.canvas.width=avatarImg.width;
          ctx.canvas.height=avatarImg.height;
          ctx.drawImage(avatarImg, 0, 0);
        };
        avatarImg.src=src;
      };
      reader.readAsDataURL(input.files[0]);
    }
  };
   return (
    <div>
      <h1>Upload an Image</h1>
        <input type="file" accept="image/*" onChange={handleFileChange} />
        <button type="submit">Upload</button>
    </div>
    );
  }  
  

 4. Show Data Url Image And Image preview


import { useState,useRef } from 'react';

export default function Home() {
  const [dataUrl, setDataUrl] = useState("");
  const [canvasVisible, setCanvasVisible] =useState(true);
  const [dataUrlVisible, setDataUrlVisible] =useState(true);
  constcanvasRef=useRef(null);
  consttextareaRef=useRef(null);
const handleFileChange = (event) => { setDataUrl(event.target.files[0]); };
  const getImageUrl=(event)=>{
    constinput=event.target;
    if (input.files&&input.files[0]) {
      constreader=newFileReader();
      reader.onload= () => {
        constavatarImg=newImage();
        constsrc=reader.result;
        setDataUrl(src);
        avatarImg.onload= () => {
          constcanvas=canvasRef.current;
          constctx=canvas.getContext("2d");
          ctx.canvas.width=avatarImg.width;
          ctx.canvas.height=avatarImg.height;
          ctx.drawImage(avatarImg, 0, 0);
        };
        avatarImg.src=src;
      };
      reader.readAsDataURL(input.files[0]);
    }
  };
 consttoggleCanvas= () => {
    setCanvasVisible(!canvasVisible);

    consttoggleDataUrl= () => {
      setDataUrlVisible(!dataUrlVisible);
    };

return ( <div> <input type='file' ref={fileInputRef} onChange={readURL} /> <br /> <br /> <button onClick={toggleCanvas}> {canvasVisible ? 'Hide canvas' : 'Show canvas'} </button> <button onClick={toggleDataUrl}> {dataUrlVisible ? 'Hide dataUrl' : 'Show dataUrl'} </button> <br /> <br /> {dataUrlVisible && ( <textarea value={dataUrl} rows="4" cols="100" readOnly /> )} <br /> {canvasVisible && <canvas ref={canvasRef} />} </div> ); }

Step 5: Conclusion and Enhancements:

Congratulations! You have successfully added image upload functionality to your Next.js application. The process involves creating a simple form, handling file uploads via an API route, and serving the uploaded images from a public directory. There are several ways to enhance this functionality: Image validation: Add checks to ensure that only image files are uploaded (e.g., checking file types and sizes).Storage options: You can store the images in cloud storage services like AWS S3 or Google Cloud Storage for better scalability.Security: Implement security measures like limiting the file size and sanitizing file names to prevent malicious uploads.By following this guide, you can provide your users with a smooth image upload experience and integrate powerful file-handling capabilities into your Next.js application. If you want to read more information about how to boost traffic on your Website just visit --> The Insider's Views.



Share

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policyTerms & Conditions