Certainly! Let's build a fully-fledged image uploader and viewer web application using Next.js. We'll extend your existing file upload API to handle image uploads, display uploaded images in a gallery, and provide functionalities to view images in detail.
Here's an outline of what we'll cover:
- Project Structure Overview
- Setting Up the Backend
- Upload API (You've provided this)
- List Images API
- Serve Images Securely
- Creating Utility Functions
- Building the Frontend
- Image Upload Page
- Image Gallery Page
- Image Viewer Component
- Handling Image Access and Security
- Final Touches and Testing
Let's dive into each step.
1. Project Structure Overview
Assuming you're using Next.js, your project structure might look like this:
my-image-app/
├── public/
│ └── images/ # Public images (you can decide to use this or a separate directory)
├── src/
│ ├── pages/
│ │ ├── api/
│ │ │ └── filesystem/
│ │ │ ├── upload.js
│ │ │ ├── list.js
│ │ │ └── getImage.js
│ │ ├── upload.js
│ │ └── gallery.js
│ ├── components/
│ │ └── ImageViewer.js
│ └── utils/
│ └── filesystem.js
├── package.json
└── ...other files
2. Setting Up the Backend
a. Upload API (Existing)
You've already provided an upload API endpoint at src/pages/api/filesystem/upload.js. Ensure it's correctly handling image uploads and storing them in a designated directory.
Important: Ensure the upload directory is not inside the public folder to prevent unauthorized access. We'll serve images via API routes for better security.
b. List Images API
Create an API endpoint to list all uploaded images.
File: src/pages/api/filesystem/list.js
// src/pages/api/filesystem/list.js
import { getSafePath } from "../../../utils/filesystem";
import fs from "fs";
import path from "path";
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Method Not Allowed" });
}
const { dir } = req.query;
if (!dir) {
return res.status(400).json({ error: "Directory is required" });
}
let safeDir;
try {
safeDir = getSafePath(dir);
} catch (error) {
console.error("Invalid path:", error);
return res.status(400).json({ error: "Invalid directory path" });
}
if (!fs.existsSync(safeDir)) {
return res.status(404).json({ error: "Directory does not exist" });
}
try {
const files = fs.readdirSync(safeDir);
const images = files.filter((file) => {
const ext = path.extname(file).toLowerCase();
return [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"].includes(ext);
});
res.status(200).json({ images });
} catch (error) {
console.error("Error reading directory:", error);
res.status(500).json({ error: "Error reading the directory" });
}
}
c. Serve Images Securely
Create an API endpoint to serve images securely. This allows you to control access and handle security concerns better.
File: src/pages/api/filesystem/getImage.js
// src/pages/api/filesystem/getImage.js
import { getSafePath } from "../../../utils/filesystem";
import fs from "fs";
import path from "path";
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Method Not Allowed" });
}
const { dir, filename } = req.query;
if (!dir || !filename) {
return res.status(400).json({ error: "Directory and filename are required" });
}
let safeDir, safeFile;
try {
safeDir = getSafePath(dir);
safeFile = path.basename(filename); // Sanitize filename
} catch (error) {
console.error("Invalid path:", error);
return res.status(400).json({ error: "Invalid path or filename" });
}
const filePath = path.join(safeDir, safeFile);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: "Image not found" });
}
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".bmp": "image/bmp",
".webp": "image/webp",
};
const mimeType = mimeTypes[ext] || "application/octet-stream";
res.setHeader("Content-Type", mimeType);
fs.createReadStream(filePath).pipe(res);
}
3. Creating Utility Functions
getSafePath Function
This function ensures that paths are sanitized to prevent directory traversal attacks. It's referenced in your existing upload API and used in the new APIs.
File: src/utils/filesystem.js
// src/utils/filesystem.js
import path from "path";
// Define the base directory where images will be stored
const BASE_DIR = path.resolve(process.cwd(), "uploads"); // Adjust as needed
/**
* Ensures the provided path is within the BASE_DIR to prevent directory traversal.
* @param {string} relativePath - The relative path provided by the user.
* @returns {string} - The absolute safe path.
* @throws {Error} - If the path is outside the BASE_DIR.
*/
export const getSafePath = (relativePath) => {
const safePath = path.normalize(relativePath).replace(/^(\.\.(\/|\\|$))+/, "");
const absolutePath = path.join(BASE_DIR, safePath);
if (!absolutePath.startsWith(BASE_DIR)) {
throw new Error("Invalid path");
}
return absolutePath;
};
Additional Setup:
Ensure the uploads directory exists. You can create it manually or programmatically.
File: src/pages/api/filesystem/init.js (Optional)
// src/pages/api/filesystem/init.js
import fs from "fs";
import path from "path";
import { getSafePath } from "../../../utils/filesystem";
export default function handler(req, res) {
const { dir } = req.query;
if (!dir) {
return res.status(400).json({ error: "Directory is required" });
}
try {
const safeDir = getSafePath(dir);
if (!fs.existsSync(safeDir)) {
fs.mkdirSync(safeDir, { recursive: true });
}
res.status(200).json({ message: "Directory initialized" });
} catch (error) {
console.error("Error initializing directory:", error);
res.status(500).json({ error: "Error initializing directory" });
}
}
You can call this API endpoint on server startup or through an admin interface to ensure directories exist.
4. Building the Frontend
We'll create two main pages:
- Upload Page: Allows users to upload images.
- Gallery Page: Displays all uploaded images in a gallery format.
a. Image Upload Page
Create a page with a form to upload images.
File: src/pages/upload.js
// src/pages/upload.js
import { useState } from "react";
export default function UploadPage() {
const [selectedFiles, setSelectedFiles] = useState([]);
const [dir, setDir] = useState("");
const [message, setMessage] = useState("");
const handleFileChange = (e) => {
setSelectedFiles(e.target.files);
};
const handleDirChange = (e) => {
setDir(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!dir) {
setMessage("Please specify a directory.");
return;
}
const formData = new FormData();
formData.append("dir", dir);
for (let i = 0; i < selectedFiles.length; i++) {
formData.append("file", selectedFiles[i]);
}
try {
const res = await fetch("/api/filesystem/upload", {
method: "POST",
body: formData,
});
const data = await res.json();
if (res.ok) {
setMessage("Files uploaded successfully!");
} else {
setMessage(`Error: ${data.error}`);
}
} catch (error) {
console.error("Upload error:", error);
setMessage("An unexpected error occurred.");
}
};
return (
<div style={containerStyle}>
<h1>Upload Images</h1>
<form onSubmit={handleSubmit} style={formStyle}>
<label>
Destination Directory:
<input
type="text"
value={dir}
onChange={handleDirChange}
placeholder="e.g., images/user1"
style={inputStyle}
required
/>
</label>
<label>
Select Images:
<input
type="file"
multiple
accept="image/*"
onChange={handleFileChange}
style={inputStyle}
required
/>
</label>
<button type="submit" style={buttonStyle}>
Upload
</button>
</form>
{message && <p>{message}</p>}
</div>
);
}
// Simple inline styles
const containerStyle = {
maxWidth: "600px",
margin: "0 auto",
padding: "20px",
textAlign: "center",
};
const formStyle = {
display: "flex",
flexDirection: "column",
gap: "15px",
alignItems: "flex-start",
};
const inputStyle = {
marginLeft: "10px",
padding: "5px",
width: "100%",
maxWidth: "300px",
};
const buttonStyle = {
padding: "10px 20px",
cursor: "pointer",
};
Notes:
- Destination Directory (
dir): Allows organizing images into subdirectories.
- Validation: Ensure proper validation on both frontend and backend.
b. Image Gallery Page
Create a page to display all uploaded images in a gallery format.
File: src/pages/gallery.js
// src/pages/gallery.js
import { useEffect, useState } from "react";
import ImageViewer from "../components/ImageViewer";
export default function GalleryPage() {
const [images, setImages] = useState([]);
const [dir, setDir] = useState("images"); // Default directory
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [selectedImage, setSelectedImage] = useState(null);
useEffect(() => {
fetchImages();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dir]);
const fetchImages = async () => {
setLoading(true);
setError("");
try {
const res = await fetch(`/api/filesystem/list?dir=${encodeURIComponent(dir)}`);
const data = await res.json();
if (res.ok) {
setImages(data.images);
} else {
setError(data.error);
setImages([]);
}
} catch (err) {
console.error("Fetch error:", err);
setError("An unexpected error occurred.");
setImages([]);
}
setLoading(false);
};
const handleDirChange = (e) => {
setDir(e.target.value);
};
const handleImageClick = (filename) => {
setSelectedImage(filename);
};
const handleCloseViewer = () => {
setSelectedImage(null);
};
return (
<div style={containerStyle}>
<h1>Image Gallery</h1>
<div style={{ marginBottom: "20px" }}>
<label>
Directory:
<input
type="text"
value={dir}
onChange={handleDirChange}
placeholder="e.g., images/user1"
style={inputStyle}
/>
</label>
<button onClick={fetchImages} style={{ ...buttonStyle, marginLeft: "10px" }}>
Load
</button>
</div>
{loading ? (
<p>Loading images...</p>
) : error ? (
<p style={{ color: "red" }}>Error: {error}</p>
) : images.length === 0 ? (
<p>No images found in this directory.</p>
) : (
<div style={galleryStyle}>
{images.map((filename) => (
<div key={filename} style={imageContainerStyle}>
<img
src={`/api/filesystem/getImage?dir=${encodeURIComponent(dir)}&filename=${encodeURIComponent(
filename
)}`}
alt={filename}
style={imageStyle}
onClick={() => handleImageClick(filename)}
/>
<p style={{ wordBreak: "break-all" }}>{filename}</p>
</div>
))}
</div>
)}
{selectedImage && (
<ImageViewer
src={`/api/filesystem/getImage?dir=${encodeURIComponent(dir)}&filename=${encodeURIComponent(
selectedImage
)}`}
alt={selectedImage}
onClose={handleCloseViewer}
/>
)}
</div>
);
}
// Simple inline styles
const containerStyle = {
maxWidth: "1200px",
margin: "0 auto",
padding: "20px",
};
const inputStyle = {
marginLeft: "10px",
padding: "5px",
width: "200px",
};
const buttonStyle = {
padding: "5px 10px",
cursor: "pointer",
};
const galleryStyle = {
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
gap: "20px",
};
const imageContainerStyle = {
textAlign: "center",
};
const imageStyle = {
width: "100%",
height: "auto",
cursor: "pointer",
borderRadius: "8px",
};
c. Image Viewer Component
Create a modal component to view images in detail.
File: src/components/ImageViewer.js
// src/components/ImageViewer.js
import React from "react";
export default function ImageViewer({ src, alt, onClose }) {
return (
<div style={overlayStyle} onClick={onClose}>
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
<img src={src} alt={alt} style={imageStyle} />
<button onClick={onClose} style={closeButtonStyle}>
Close
</button>
</div>
</div>
);
}
const overlayStyle = {
position: "fixed",
top: 0,
left: 0,
width: "100vw",
height: "100vh",
backgroundColor: "rgba(0,0,0,0.7)",
display: "flex",
justifyContent: "center",
alignItems: "center",
zIndex: 1000,
};
const modalStyle = {
position: "relative",
backgroundColor: "#fff",
padding: "20px",
borderRadius: "8px",
maxWidth: "90%",
maxHeight: "90%",
overflow: "auto",
};
const imageStyle = {
maxWidth: "100%",
maxHeight: "80vh",
};
const closeButtonStyle = {
position: "absolute",
top: "10px",
right: "10px",
padding: "5px 10px",
cursor: "pointer",
};
5. Handling Image Access and Security
a. Preventing Unauthorized Access
If your application requires authentication, ensure that all API routes check for authentication tokens or sessions before proceeding.
Example:
// src/pages/api/filesystem/upload.js
import { getSession } from "next-auth/client"; // If using next-auth
export default async function handler(req, res) {
const session = await getSession({ req });
if (!session) {
return res.status(401).json({ error: "Unauthorized" });
}
// ... rest of the upload code
}
Adjust according to your authentication method.
b. Validating Image Files
Ensure that uploaded files are indeed images to prevent security issues.
Modify the Upload Handler: In your upload API, add validation for file types.
// Inside the upload handler, before moving the file
const allowedTypes = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"];
const ext = path.extname(fileName).toLowerCase();
if (!allowedTypes.includes(ext)) {
console.warn(`File "${fileName}" has unsupported file type. Skipping upload.`);
continue; // Skip this file
}
6. Final Touches and Testing
a. Ensure Uploads Directory Exists
Make sure the uploads directory exists at the root of your project or wherever you set it in getSafePath.
Optional: Create a script to initialize directories.
File: scripts/initUploads.js
// scripts/initUploads.js
const fs = require("fs");
const path = require("path");
const uploadDir = path.resolve(process.cwd(), "uploads", "images");
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
console.log(`Created directory: ${uploadDir}`);
} else {
console.log(`Directory already exists: ${uploadDir}`);
}
Run:
Add a script to package.json:
"scripts": {
"init-uploads": "node scripts/initUploads.js",
// ... other scripts
}
Then run:
npm run init-uploads
# or
yarn init-uploads
b. Styling and UI Enhancements
For a better user experience, consider using a CSS framework like Tailwind CSS or Material-UI to enhance the UI.
c. Testing
- Upload Images: Go to
/upload, select images, specify a directory (e.g., images/user1), and upload.
- View Gallery: Navigate to
/gallery, enter the same directory (images/user1), and view the uploaded images.
- Image Viewer: Click on any image thumbnail to view it in detail.
- Edge Cases:
- Uploading non-image files (should be skipped).
- Uploading images with duplicate names (currently skipped).
- Accessing images from invalid directories (should return errors).
Complete Example: Putting It All Together
Here's a complete example assuming you have a Next.js project set up.
1. Install Dependencies
Ensure you have the necessary packages installed.
npm install formidable
# or
yarn add formidable
2. Update next.config.js (Optional)
If you're serving large files or need to adjust API route settings, modify your next.config.js.
// next.config.js
module.exports = {
api: {
bodyParser: false, // Already set in your upload API
},
// Other Next.js configurations
};
3. Run the Development Server
npm run dev
# or
yarn dev
Visit http://localhost:3000/upload to upload images and http://localhost:3000/gallery to view them.
Additional Enhancements
- Thumbnail Generation: Generate and serve thumbnails for faster gallery loading.
- Image Cropping and Resizing: Allow users to crop or resize images upon upload.
- Pagination: Implement pagination for directories with a large number of images.
- Search and Filters: Enable searching and filtering images based on metadata.
- User Authentication: Integrate user authentication to manage access control.
- Drag-and-Drop Uploads: Enhance the upload page with drag-and-drop support.
- Progress Indicators: Show upload progress for better UX.
Conclusion
You've now built a complete image uploader and viewer application using Next.js. This setup ensures that images are uploaded securely, stored in organized directories, and served efficiently to clients. Remember to handle all edge cases and continuously test your application to maintain security and performance.
If you have further requirements or need more advanced features, consider integrating additional tools and services tailored to your specific use case.
Feel free to ask if you need further assistance or have specific questions!