In modern web applications, file upload functionality is an essential feature, whether you're dealing with profile pictures, documents, or other data. One of the most common and efficient ways to handle file uploads is through multipart/form-data encoding. In this post, we’ll walk through how to implement multipart file upload using Java (backend) and JavaScript (frontend) with practical code examples and best practices.
📂 What is Multipart File Upload?
Multipart upload is a method that allows users to send files from the frontend to the server by breaking them into parts. The multipart/form-data content type is used to transfer file data in HTTP POST requests, and it supports sending multiple files or combining files with other form fields.
🧱 Project Setup
Let’s assume you are building a web application with a Java backend (Spring Boot) and a frontend built using plain HTML and JavaScript (or any framework like React).
🎯 Frontend: JavaScript Code to Upload a File
Here’s a basic HTML form with JavaScript code to handle file input and send it using fetch() API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h2>Upload File</h2>
<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
<script>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append("file", file);
fetch("http://localhost:8080/upload", {
method: "POST",
body: formData
})
.then(response => response.text())
.then(result => alert("Success: " + result))
.catch(error => alert("Error: " + error));
}
</script>
</body>
</html>
✅ Key Points:
- FormData() is used to package the file.
- The fetch() API sends a POST request to the Java backend.
- No need to manually set headers like Content-Type; the browser handles it.
☕ Backend: Java with Spring Boot
In your Spring Boot project, add the following dependencies in pom.xml (for Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Then create a controller to handle file uploads:
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
Path path = Paths.get("uploads/" + fileName);
Files.createDirectories(path.getParent());
Files.write(path, file.getBytes());
return ResponseEntity.ok("File uploaded successfully: " + fileName);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("File upload failed");
}
}
}
🔐 Don’t Forget:
- Ensure multipart is enabled in your application.properties:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
- Create the uploads/ directory or handle it dynamically as in the code.
🚀 Best Practices
- File Validation: Always validate file type and size before processing to prevent malicious uploads.
- Storage Strategy: For production, consider cloud storage (AWS S3, Azure Blob) instead of local disk.
- Progress Feedback: Implement progress bars using XMLHttpRequest or the fetch() API with ReadableStream.
- Security: Sanitize file names to avoid directory traversal attacks.
✅ Final Thoughts
Implementing multipart file upload using Java and JavaScript is straightforward once you understand the flow: collect the file on the client side, send it as multipart/form-data, and process it on the backend. With tools like Spring Boot and modern browser APIs, it's easier than ever to build a secure and efficient file upload feature.
If you're building a web application that requires file uploads, integrating this feature will improve user experience and enable powerful functionality. Stay tuned for advanced tips on handling large file uploads and integrating cloud storage solutions!
'개발지식' 카테고리의 다른 글
How to Parse JSON in Java Using Gson – A Complete Guide (0) | 2025.04.17 |
---|---|
Understanding the Difference Between schedule() and scheduleAtFixedRate() in Java Timer (0) | 2025.04.14 |
Mastering Oracle Timestamp and Date Conversion Functions: A Complete Guide (0) | 2025.04.12 |
Docker Nodejs 설치 명령어 사용방법 (0) | 2024.04.01 |
JPA란? 간단하게 파헤치기! (0) | 2024.03.11 |