Hackforge Academy

Category: java

Uploading Files with MultipartFile

Published on 24 Jul 2026

Explanation

Spring Boot provides the MultipartFile interface to upload files through REST APIs. Uploaded files can be stored on the local file system, cloud storage, or a database depending on application requirements.

Code:

@PostMapping("/upload")
public String uploadFile(@RequestParam MultipartFile file) {
    return file.getOriginalFilename();
}

Explanation

To download files, Spring Boot returns a Resource object wrapped inside a ResponseEntity. Appropriate HTTP headers, such as Content-Disposition, instruct the browser to download the file instead of displaying it.

Code:

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
    Resource file = new FileSystemResource("report.pdf");
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=report.pdf")
            .body(file);
}

Explanation

Spring Boot integrates with JavaMailSender to send emails. Configure SMTP settings such as host, port, username, and password in application.properties to connect to an email provider like Gmail or Outlook.

Code:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-app-password

Explanation

The JavaMailSender interface is used to send plain text or HTML emails. It creates a SimpleMailMessage, sets the recipient, subject, and message, then sends it through the configured SMTP server.

Code:

@Autowired
private JavaMailSender mailSender;

public void sendEmail() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo("user@example.com");
    message.setSubject("Welcome");
    message.setText("Registration Successful");
    mailSender.send(message);
}

Explanation

A common enterprise workflow is to upload a file successfully and immediately send an email notification to the user. Spring Boot combines MultipartFile for file handling and JavaMailSender for email notifications within the same service.

Code:

@PostMapping("/documents")
public String uploadDocument(@RequestParam MultipartFile file) {
    fileService.save(file);
    emailService.sendEmail();
    return "File uploaded successfully";
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community