DEV Community

Sh Raj
Sh Raj

Posted on

Handling File Uploads in Next.js Using UploadThing

Handling File Uploads in Next.js Using UploadThing

File uploads are a common feature in many web applications, and handling them efficiently and securely is crucial. In this article, we'll explore how to handle file uploads in a Next.js application using UploadThing, a powerful and easy-to-use library for managing file uploads.

Table of Contents

  1. Introduction to UploadThing
  2. Setting Up a Next.js Project
  3. Installing UploadThing
  4. Configuring UploadThing
  5. Creating the Upload Component
  6. Handling File Uploads
  7. Displaying Uploaded Files
  8. Conclusion

1. Introduction to UploadThing

UploadThing is a robust library designed to simplify the process of file uploads in web applications. It provides a straightforward API for handling file uploads, along with features for file validation, progress tracking, and more.

2. Setting Up a Next.js Project

First, let's set up a basic Next.js project. If you already have a Next.js project, you can skip this step.

npx create-next-app@latest file-upload-nextjs
cd file-upload-nextjs
npm run dev
Enter fullscreen mode Exit fullscreen mode

3. Installing UploadThing

To use UploadThing in your Next.js project, you'll need to install it via npm or yarn.

npm install uploadthing
Enter fullscreen mode Exit fullscreen mode

or

yarn add uploadthing
Enter fullscreen mode Exit fullscreen mode

4. Configuring UploadThing

Next, we'll configure UploadThing in our Next.js project. Create a new file named uploadthing.config.js in the root directory of your project.

// uploadthing.config.js
import { configureUpload } from 'uploadthing';

export default configureUpload({
  destination: '/uploads', // Directory where files will be uploaded
  maxSize: 10 * 1024 * 1024, // Max file size in bytes (10 MB)
  allowedFormats: ['image/jpeg', 'image/png', 'application/pdf'], // Allowed file formats
});
Enter fullscreen mode Exit fullscreen mode

5. Creating the Upload Component

Let's create a simple upload component that allows users to select and upload files. Create a new file named UploadComponent.js in the components directory.

// components/UploadComponent.js
import { useState } from 'react';
import { uploadFile } from 'uploadthing';

const UploadComponent = () => {
  const [file, setFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadedFile, setUploadedFile] = useState(null);

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
  };

  const handleUpload = async () => {
    if (file) {
      try {
        const result = await uploadFile(file, {
          onProgress: (progress) => setUploadProgress(progress),
        });
        setUploadedFile(result);
        alert('File uploaded successfully!');
      } catch (error) {
        console.error('Error uploading file:', error);
        alert('Failed to upload file.');
      }
    }
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleUpload}>Upload</button>
      {uploadProgress > 0 && <p>Upload Progress: {uploadProgress}%</p>}
      {uploadedFile && <p>File uploaded: {uploadedFile.url}</p>}
    </div>
  );
};

export default UploadComponent;
Enter fullscreen mode Exit fullscreen mode

6. Handling File Uploads

The UploadComponent handles file uploads by calling the uploadFile function from the UploadThing library. It also tracks the upload progress and displays it to the user.

7. Displaying Uploaded Files

Once a file is uploaded, you can display it in your application. In the example above, the uploaded file's URL is stored in the uploadedFile state and displayed to the user.

8. Conclusion

Handling file uploads in Next.js using UploadThing is straightforward and efficient. By following the steps outlined in this article, you can easily integrate file upload functionality into your Next.js applications, providing a seamless user experience.

UploadThing offers a range of features to enhance your file upload handling, including file validation, progress tracking, and more. Explore the UploadThing documentation for additional options and advanced configurations to suit your specific needs.

Happy coding!

Top comments (0)