The Power of Typography in Web Design: Making Text Easy to Read
Good typography can make a big difference in how users interact with your site. Let's explore why typography matters and how to use it effectively.
Read moreby Tajbin Khan Evan, Full Stack Developer
FormData is an essential part of modern web applications, allowing developers to handle form submissions effectively, especially when dealing with file uploads. In this guide, we’ll explore how to work with FormData in a Next.js application, both on the client side and server side, using the powerful Next.js app router.
FormData is a built-in JavaScript object that can construct key/value pairs representing form fields and their values. This object is particularly useful for sending form data, including files, to a server via an HTTP request.
First, let’s set up a basic Next.js project. If you haven’t already, install the Next.js framework:
npx create-next-app@latest my-formdata-app
cd my-formdata-app
In this section, we’ll create a form that includes text inputs and a file upload input. We’ll then use FormData to handle the form submission.
Create a new component, UploadForm.js, inside the components directory:
// components/UploadForm.js
import { useState } from 'react';
const UploadForm = () => {
const [formData, setFormData] = useState({
name: '',
file: null,
});
const handleChange = (e) => {
const { name, value, files } = e.target;
if (name === 'file') {
setFormData({ ...formData, file: files[0] });
} else {
setFormData({ ...formData, [name]: value });
}
};
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData();
data.append('name', formData.name);
data.append('file', formData.file);
const response = await fetch('/api/upload', {
method: 'POST',
body: data,
});
if (response.ok) {
alert('File uploaded successfully');
} else {
alert('File upload failed');
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" value={formData.name} onChange={handleChange} required />
<input type="file" name="file" onChange={handleChange} required />
<button type="submit">Upload</button>
</form>
);
};
export default UploadForm;
Create a new page, pages/index.js, and include the UploadForm component:
// pages/index.js
import UploadForm from '../components/UploadForm';
import UploadForm from '../components/UploadForm';
const Home = () => (
<div>
<h1>Upload Your File</h1>
<UploadForm />
</div>
);
export default Home;
Next.js allows us to handle API routes easily. We’ll create an API endpoint to handle the form submission.
// pages/api/upload.js
import formidable from 'formidable';
import formidable from 'formidable';
import fs from 'fs';
export const config = {
api: {
bodyParser: false,
},
};
export default function handler(req, res) {
if (req.method === 'POST') {
const form = new formidable.IncomingForm();
form.uploadDir = './public/uploads'; // Ensure this directory exists
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
res.status(500).json({ error: 'File upload error' });
return;
}
const oldPath = files.file.filepath;
const newPath = `./public/uploads/${files.file.originalFilename}`;
fs.rename(oldPath, newPath, (err) => {
if (err) {
res.status(500).json({ error: 'File rename error' });
return;
}
res.status(200).json({ message: 'File uploaded successfully' });
});
});
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}
Handling FormData in Next.js is straightforward with the app router. By following this guide, you’ve learned how to create a form with file uploads on the client side and process those uploads on the server side. This approach ensures a seamless experience for users uploading files to your Next.js application. Consider integrating additional features like validation, progress tracking, and error handling for more advanced handling. Happy coding!
Our team of experienced designers and developers has just one thing on their mind; working on your ideas to draw a smile on the face of your users worldwide. From conducting Brand Sprints to UX Design.
Good typography can make a big difference in how users interact with your site. Let's explore why typography matters and how to use it effectively.
Read morePopular UI patterns and graphic styles in modern web design emphasize minimalism, responsiveness, and user-centric elements, incorporating trends like dark mode, bold typography, and microinteractions.
Read more