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:
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.
@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**/
@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 Exception, Repository, File Response and Error Constants classes.
And Finally ! Here comes an interesting part of the whole application.
#spring #database #rest-api #spring-boot #java #api