Let us try to achieve file uploading and downloading using Java 8, Hibernate and PostgreSQL

This article helps to perform Upload and Download action of files regardless of file format. REST endpoints that is generated can be consumed in any front-end frameworks like React js, Angular or Vue js and etc…

Configuring Database properties

First and foremost, create a Spring project by using either Spring Initializer or Spring Tool Suite. Make sure that the folder structure looks like below:

Image for post

Project Structure

All Right!. First, let us try to configure database properties in application.properties file.

server.port=8090

#Hibernate database config
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.driver-class-name=org.postgresql.Driver

#Provide the username&password of your database
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

#Multipart file config
spring.servlet.multipart.enabled=true

## Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
## Max file size.
spring.servlet.multipart.max-file-size=800MB
## Max Request Size
spring.servlet.multipart.max-request-size=800MB

As you can see above, we have also set the file size,threshold limit and request size using spring-multipart property.

  • Create a File model class mentioning file fields to be stored in database.
@Entity
@Table(name = "fileuploadDownload")
public class FileModel {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")

    private String fileId;
    private String fileName;
    private String fileType;
    @Lob
    private byte[] fileData;
    public FileModel() {

    }
    public FileModel(String fileName, String fileType) {
        this.fileName = fileName;
        this.fileType = fileType;

    }
    public FileModel(String fileName, String fileType, byte[] fileData)     {
        this.fileName = fileName;
        this.fileType = fileType;
        this.fileData = fileData;
    }
/**Getters and Setters**/
  • Next, Create a Service class which will contain methods to retrieve file information to (or) from the database.
@Service
public class FileService {

    @Autowired
    FileRepo fileRepo;
    public FileModel saveFile(MultipartFile file) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            if (filename.contains("...")) {
                throw new FileSaveException(FileErrors.INVALID_FILE + filename);
            }
            FileModel model = new FileModel(filename, file.getContentType(), file.getBytes());
            return fileRepo.save(model);

        } catch (Exception e) {
            throw new FileSaveException(FileErrors.FILE_NOT_STORED, e);
        }
    }

    public FileModel getFile(String fileId) {
        return fileRepo.findById(fileId).orElseThrow(() -> new FileNotFoundException(FileErrors.FILE_NOT_FOUND + fileId));
    }
    public List<FileModel> getListOfFiles(){
        return fileRepo.findAll();
    }
}

You can also visit here, to find how to create ExceptionRepository, File Response and Error Constants classes.

And Finally ! Here comes an interesting part of the whole application.

Image for post

  • Create a Controller class which will define all the REST endpoints required for our application.

#spring #database #rest-api #spring-boot #java #api

File Upload and Download-Java 8 Hibernate and PostgreSQL
4.50 GEEK