How To Upload And Download File To API In Next JS Application

Introduction

This article will teach us how to upload a file to the web API in the Next JS application using Axios. We also learn how to download a file in the Next JS application.

Preconditions

  • Javascript
  • Basic knowledge of Next JS
  • Node.js
  • V.S. Code,Visual Studio

We cover the below things,

  • Create Next JS application
  • Upload File to API using axios in Next Js
  • Download the File in Next JS

Step 1

Run the below code to create the Next JS application.

npx create-next-app nextjsappfileuploadanddownload
cd nextjsappfileuploadanddownload
npm run dev

Step 2

Run the below command for installing Axios.

npm i axios

Create the file according to the below image.

How to upload and download file to API in Next Js application

Step 3

Add the below code in the index.js.

import { useState } from 'react';
import axios from "axios";
import { Col, Row } from 'react-bootstrap';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';

const MyFileUpload = () => {
        const [file, setFile] = useState(null);
        const UPLOAD_ENDPOINT = "http://localhost/react-php-file-upload/backend/upload.php";
        const DOWNLOAD_ENDPOINT = "http://localhost/react-php-file-upload/backend/upload.php";
        const handleSubmit = (e) => {
            debugger
            e.preventDefault();
            console.log(file)
            //if await is removed, console log will be called before the uploadFile() is executed completely.
            //since the await is added, this will pause here then console log will be called
            const formData = new FormData();
            formData.append("myfile", file, file.name);
            axios.post(UPLOAD_ENDPOINT, formData, {
                headers: {
                    "content-type": "multipart/form-data"
                }
            }).then(data => {
                debugger
                console.log(data.data);
            });
        };
        const handleOnChange = e => {
            console.log(e.target.files[0]);
            setFile(e.target.files[0]);
        };
        const DownloadFile = () => {
            debugger
            axios.post(DOWNLOAD_ENDPOINT, formData).then(data => {
                debugger
                console.log(data.data);
            });
        }
        const handleDownload = (url, filename) => {
            axios.get(url, {
                responseType: 'blob',
            }).then((res) => {
                fileDownload(res.data, filename)
            })
        }
    return (
        <div>
            <Row>
                <Col lg={6}>
                    <div className='card text-center' style={{ padding: '30px', background: 'rgb(220 191 233)' }}>
                        <form action='form' onSubmit={handleSubmit}>
                            <div>
                                <h3>Select your files</h3>
                                <input
                                    type="file"

                                    // To select multiple files
                                    //multiple="multiple"
                                    onChange={(e) => handleOnChange(e)}
                                />

                            </div>
                            <button className='btn btn-primary' >
                                Send Files
                            </button>
                        </form>
                    </div>

                </Col>
                <Col lg={6}>
                    <div className='card text-center' style={{ padding: '44px', background: 'rgb(220 191 233)' }}>
                        <h3>Open File in new tab</h3>
                        <a type="button" 
    className="btn btn-secondary btn-lg" target="_blank"  href='https://www.africau.edu/images/default/sample.pdf' >Open
 </a>
                       
                    </div>

                </Col>
            </Row>

        </div>
    )
}
export default MyFileUpload

Step 4

Add the below code in MyFileUpload.js.

import { useState } from 'react';
import axios from "axios";
import { Col, Row } from 'react-bootstrap';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';

const MyFileUpload = () => {
        const [file, setFile] = useState(null);
        const UPLOAD_ENDPOINT = "http://localhost/react-php-file-upload/backend/upload.php";
        const DOWNLOAD_ENDPOINT = "http://localhost/react-php-file-upload/backend/upload.php";
        const handleSubmit = (e) => {
            debugger
            e.preventDefault();
            console.log(file)
            //if await is removed, console log will be called before the uploadFile() is executed completely.
            //since the await is added, this will pause here then console log will be called
            const formData = new FormData();
            formData.append("myfile", file, file.name);
            axios.post(UPLOAD_ENDPOINT, formData, {
                headers: {
                    "content-type": "multipart/form-data"
                }
            }).then(data => {
                debugger
                console.log(data.data);
            });
        };
        const handleOnChange = e => {
            console.log(e.target.files[0]);
            setFile(e.target.files[0]);
        };
        const DownloadFile = () => {
            debugger
            axios.post(DOWNLOAD_ENDPOINT, formData).then(data => {
                debugger
                console.log(data.data);
            });
        }

    return (
        <div>
            <Row>
                <Col lg={6}>
                    <div className='card text-center' style={{ padding: '30px', background: 'rgb(220 191 233)' }}>
                        <form action='form' onSubmit={handleSubmit}>
                            <div>
                                <h3>Select your files</h3>
                                <input
                                    type="file"

                                    // To select multiple files
                                    //multiple="multiple"
                                    onChange={(e) => handleOnChange(e)}
                                />

                            </div>
                            <button className='btn btn-primary' >
                                Send Files
                            </button>
                        </form>
                    </div>

                </Col>
                <Col lg={6}>
                    <div className='card text-center' style={{ padding: '44px', background: 'rgb(220 191 233)' }}>
                        <h3>Download file</h3>
                        <button className='btn btn-primary' onClick={DownloadFile}>Download</button>
                    </div>

                </Col>
            </Row>

        </div>
    )
}
export default MyFileUpload

Step 5

Create Home.module.css and globals.css. You can find the CSS code with the attached source code.

Step 6

Add the following code in package.json.

{
    "name": "nextjsappfileuploadanddownload",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
    },
    "dependencies": {
        "axios": "^1.3.4",
        "bootstrap": "^5.2.3",
        "next": "13.2.4",
        "react": "18.2.0",
        "react-bootstrap": "^2.7.2",
        "react-dom": "18.2.0"
    }
}

Step 7

Run the following commands.

npm i
npm run dev

How to upload and download file to API in Next Js application

Summary

This article taught us how to create the Next JS project and upload files using Axios. Also, we learned how to download files from a path in Next JS.


Similar Articles