Spring Boot File Upload and Store in Database

In this tutorial, we will create a REST API for uploading files and storing them in a database using Spring Boot 3. We will use Spring Data JPA to interact with the database and store file metadata along with the file content.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
  • A relational database (e.g., MySQL, PostgreSQL)

Step 1: Setting Up the Spring Boot Project

1.1 Create a Spring Boot Project

  1. Open Spring Initializr:

  2. Configure Project Metadata:

    • Project: Maven Project
    • Language: Java
    • Spring Boot: Select the latest version of Spring Boot 3
    • Group: com.example
    • Artifact: file-upload-db
    • Name: file-upload-db
    • Description: File Upload and Store in Database with Spring Boot
    • Package Name: com.example.fileuploaddb
    • Packaging: Jar
    • Java Version: 17 (or your preferred version)
    • Click Next.
  3. Select Dependencies:

    • On the Dependencies screen, select the dependencies you need:
      • Spring Web
      • Spring Data JPA
      • Spring Boot DevTools
      • Your database driver (e.g., MySQL, PostgreSQL)
    • Click Next.
  4. Generate the Project:

    • Click Generate to download the project zip file.
    • Extract the zip file to your desired location.
  5. Open the Project in Your IDE:

    • Open your IDE and import the project as a Maven project.

1.2 Update application.properties

Open the application.properties file located in the src/main/resources directory and add the following configuration:

# Database configuration (example for MySQL)
spring.datasource.url=jdbc:mysql://localhost:3306/filedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Replace the database URL, username, and password with your database configuration.

Step 2: Implementing the File Entity and Repository

2.1 Create the FileEntity Class

In the com.example.fileuploaddb.model package, create a new Java class named FileEntity:

package com.example.fileuploaddb.model;

import jakarta.persistence.*;

@Entity
public class FileEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String fileName;

    private String fileType;

    @Lob
    private byte[] data;

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
}

2.2 Create the FileRepository Interface

In the com.example.fileuploaddb.repository package, create a new Java interface named FileRepository:

package com.example.fileuploaddb.repository;

import com.example.fileuploaddb.model.FileEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface FileRepository extends JpaRepository<FileEntity, Long> {
}

Step 3: Implementing the File Service

3.1 Create the FileStorageService Class

In the com.example.fileuploaddb.service package, create a new Java class named FileStorageService:

package com.example.fileuploaddb.service;

import com.example.fileuploaddb.model.FileEntity;
import com.example.fileuploaddb.repository.FileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Optional;

@Service
public class FileStorageService {

    private final FileRepository fileRepository;

    @Autowired
    public FileStorageService(FileRepository fileRepository) {
        this.fileRepository = fileRepository;
    }

    public FileEntity storeFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();

        try {
            FileEntity fileEntity = new FileEntity();
            fileEntity.setFileName(fileName);
            fileEntity.setFileType(file.getContentType());
            fileEntity.setData(file.getBytes());

            return fileRepository.save(fileEntity);
        } catch (IOException ex) {
            throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

    public Optional<FileEntity> getFile(Long fileId) {
        return fileRepository.findById(fileId);
    }
}

Step 4: Creating the REST Controller

4.1 Create the FileController Class

In the com.example.fileuploaddb.controller package, create a new Java class named FileController:

package com.example.fileuploaddb.controller;

import com.example.fileuploaddb.model.FileEntity;
import com.example.fileuploaddb.service.FileStorageService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/files")
public class FileController {

    private final FileStorageService fileStorageService;

    public FileController(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        FileEntity fileEntity = fileStorageService.storeFile(file);
        return ResponseEntity.ok("File uploaded successfully: " + fileEntity.getFileName());
    }

    @GetMapping("/download/{fileId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable Long fileId) {
        FileEntity fileEntity = fileStorageService.getFile(fileId)
                .orElseThrow(() -> new RuntimeException("File not found with id " + fileId));

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(fileEntity.getFileType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileEntity.getFileName() + "\"")
                .body(fileEntity.getData());
    }
}

4.2 Create the FileUploadDownloadDbApplication Class

Ensure the FileUploadDownloadDbApplication class is present in the src/main/java/com/example/fileuploaddb directory:

package com.example.fileuploaddb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FileUploadDownloadDbApplication {

    public static void main(String[] args) {
        SpringApplication.run(FileUploadDownloadDbApplication.class, args);
    }
}

Step 5: Running the Application

  1. Open the FileUploadDownloadDbApplication class in the src/main/java/com/example/fileuploaddb directory.

  2. Click the green Run button in your IDE or use the terminal to run the application:

    ./mvnw spring-boot:run
    
  3. The application will start on http://localhost:8080.

Step 6: Testing the Application

You can use tools like Postman to test the file upload and download functionality.

6.1 Upload a File

  1. Open Postman.
  2. Create a new POST request to http://localhost:8080/api/files/upload.
  3. In the Body tab, select form-data.
  4. Add a key file and select a file to upload.
  5. Send the request.

6.2 Download a File

  1. Open Postman.
  2. Create a new GET request to http://localhost:8080/api/files/download/{fileId}.
    • Replace {fileId} with the ID of the file you uploaded.
  3. Send the request and verify that the file is downloaded.

Conclusion

In this tutorial, we created a REST API for uploading files and storing them in a database using Spring Boot 3. We implemented file storage, upload, and download functionalities and tested the API using Postman. This setup provides a solid foundation for developing more complex file management systems.


Comments