File Upload with Progress Bar in Next.js
Provide an example of a file upload component using Next.js with a visual progress bar indicating the upload status.
import { useState } from 'react';
import axios from 'axios';
export default function FileUpload() {
const [selectedFile, setSelectedFile] = useState(null);
const [uploadProgress, setUploadProgress] = useState(0);
const onFileChange = (event) => {
setSelectedFile(event.target.files[0]);
setUploadProgress(0);
};
const onFileUpload = () => {
const formData = new FormData();
formData.append(
'myFile',
selectedFile,
selectedFile.name
);
axios.post('/api/upload', formData, {
onUploadProgress: progressEvent => {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setUploadProgress(percentCompleted);
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.error(err);
});
};
return (
<>
<input type='file' onChange={onFileChange} />
<button onClick={onFileUpload}>Upload</button>
{ selectedFile && <div>{uploadProgress}%</div> }
<div style={{ width: `${uploadProgress}%`, background: 'blue', height: '5px' }} />
</>
);
}
This is a React component for file upload with a progress bar using Next.js. It uses axios for sending the file to the server and updates the progress bar during the upload.
export default function handler(req, res) {
if (req.method === 'POST') {
// Handle the file upload process
// You will need to use a middleware like 'multiparty' or 'formidable'
// for parsing form data including file uploads
// res.status(200).json({ status: 'success', message: 'File uploaded successfully!' });
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
This is an API route handler in Next.js for the file upload. Here you would use middleware to handle the file upload, then respond with success or handle errors appropriately. Uncomment the res.status(200).json line and include your upload logic.