Rest API java spring — Upload text and pdf to PostgreSQL database (postman — form data)
I am making a REST API in Java spring. I want to make a post request in postman and upload some text and a pdf file to my postgreSQL database. The connection works. I tested it with another endpoint. I tried alot of things but none of them works.
I heard you can do this with postman — Form data.
What I tried: added this to the @PostMapping() —> No success
In postman: added Content-type : application/json and Content-type : multipart/form-data
Spring Boot upload file to PostgreSQL database
In this article, we will present how to create a Spring Boot application that uploads a file to the PostgreSQL database. The server application based on REST architecture will use Spring Data JPA for executing queries on the database and MultipartFile interface for handling multi-part requests.
2. Technology
Spring Boot application will use the following technology stack:
- Java 8
- Spring Boot 2
- Spring Data JPA
- PostgreSQL
- Maven 3.6.1
3. Project structure
- FileEntity class that is a data model entity object related to a table in the PostgreSQL database,
- FileResponse is a POJO object used to listing files,
- FileRepository is a Spring Data repository used to save and retrieve files to/from the database,
- FileService is our service that will be calling methods from FileRepository ,
- FilesController used to handle HTTP requests like POST (for uploading files), GET (for listing and downloading files),
- RestExceptionHandler class handles exceptions that could occur when processing requests,
- application.properties is a Spring Boot configuration file used to setup database connection and set file upload size limits,
- pom.xml for project dependencies.
4. REST API for uploading/downloading files
The Spring Boot application will provide a fully REST-ful API for:
- uploading files to PostgreSQL database,
- downloading files from the database,
- retrieving a list of uploaded files.
Spring Boot application will provide the following API endpoints:
| URL | Method | Action |
| /files | GET | Get list of uploaded files |
| /files | POST | Upload a single file |
| /files/ | GET | Download uploaded file |
Files will be downloaded directly to the database with informations like:
- name of the file,
- size of the file,
- generated UUID to identify the uploaded file,
- file content as BLOB,
- file content type.
5. Configure Spring Boot project
First, we need to create a Spring Boot project using initializer or with IDE like Eclipse, IntelliJ where we can simply create a new Maven project.
Then, we need to add Spring Boot web and Spring JPA starter dependencies to our pom.xml file:
The org.postgresql:postgresql library is used for interactions with the PostgreSQL database.
For the latest versions of this dependecies check the following links:
6. Create Model Entity
Entity objects correspond to database tables. In our project we created a FileEntity class that will be related to the FILES table:
Two fields were marked with special annotations:
- id — @Id , @GeneratedValue(generator = "uuid") , @GenericGenerator(name = "uuid", strategy = "uuid2") — this field will have auto-generated UUID,
- data — @Lob special datatype that informs about storing large objects in the database.
Second POJO class used in model layer is FileResponse :
This object will be used to present a list of files with detailed information about them, such as name, content type, size.
7. Implement data access layer
In our data access layer, we have an interface FileRepository that extends JpaRepository . Thanks to this, we have access to crud methods like save(. ) , getById(. ), delete(. ) etc.
8. Create service for managing files
The FileService class will be responsible for:
- saving uploaded files (transforming MultipartFile object into FileEntity),
- uploading a single file by provided id,
- return a list of uploaded files.
In most cases FileService just calls methods from FileRepository but it is a good place for future business logic.
9. Create a REST controller for handing HTTP requests
The FilesController will be responsible for handling HTTP requests.
This class has been marked with the following annotations:
- @RestController — annotation is used to treat this class as a REST controller,
- @RequestMapping — create a base endpoint to /files URI.
Other annotations used in this class like @GetMapping , @PostMapping and @DeleteMapping — are for mapping HTTP GET, POST and DELETE requests with specific class methods:
| HTTP Method | Endpoint | Method |
| POST | /files | upload(. ) |
| GET | /files | list(. ) |
| GET | /files/ | getFile(. ) |
10. Configure JPA, Hibernate and file size upload limits
In the application.properties file we created a several entries:
We used the following properties:
- spring.datasource.url — to define a datasource,
- spring.datasource.username — database username,
- spring.datasource.password — database password,
- spring.jpa.hibernate.ddl-auto can be:
- none — no change is made to the database structure,
- update — Hibernate will change the database according to the given entity structures,
- create — this will creates the database every time on server start,
- create-drop — creates the database and drops it when SessionFactory closes.
11. Create exception handler
The class annotated with @ControllerAdvice is responsible for handling exceptions that may occur during the uploading files process:
We handle just MaxUploadSizeExceededException but this could be extended to some other exceptions as well.
12. Main Spring Boot starting server class
The main Spring Boot application class that starts the server has the following structure:
13. Testing Application API
To run the Spring Boot server use mvn spring-boot:run command or find the generated jar in the /target folder and type java -jar upload-file-to-postgresql-0.0.1-SNAPSHOT.jar .
When everything is correctly configured You should see information about the started server:
Also in the database, there should be a new table called FILES with the following structure:
We will use Postman to make some API requests.
13.1. First, let's upload some file

In the FILES table a new record appeared:

13.2. Now check a list of uploaded files

13.3. Finally, download the upload file using a provided URL

14. Conclusion
In this tutorial, we presented step by step how to create a Spring Boot application that will upload files to the PostgreSQL database.
As usual, the code used in this tutorial is available in our GitHub repository.
Как сохранить файл pdf в базе данных postgresql с помощью сервлетов?
При отправке формы вызывается сервлет pdf. Внутри сервлета объект запроса анализируется, и файл (pdf) читается с использованием InputStream, как указано в коде ниже.
Как видите, я использовал объект InputStream для проверки формата файла как pdf.
Теперь я хочу сохранить этот PDF-файл в базе данных postgresql. Какое поле следует использовать в postgresql и как получить файл из объекта InputStream, чтобы сохранить его в базе данных?
2 ответа
Непонятно, какой API персистентности вы используете. JDBC? JPA? Старый добрый Hibernate? Я предполагаю, что JDBC. В JDBC вы можете использовать PreparedStatement#setBinaryStream() , чтобы сохранить InputStream в базе данных, или PreparedStatement#setBytes() , чтобы сохранить byte[] в базе данных. В любом случае в PostgreSQL вам понадобится bytea столбец для этого.
Поскольку вы сначала проверяете загруженный файл с помощью PdfReader , InputStream не подходит. А именно его можно прочитать только один раз. Клиент не собирается повторно отправлять файл несколько раз каждый раз, когда вам нужно будет снова прочитать InputStream . Сначала вам нужно скопировать InputStream в byte[] .
( IOUtils является частью Apache Commons IO; если вы используете FileUpload, значит, он у вас уже есть)
Не забудьте изменить iText, чтобы вместо него использовался byte[] :
После того, как вы проверили его с помощью iText, вы можете сохранить его в столбце PostgreSQL bytea с помощью JDBC следующим образом:
В этом форум. Он использует изображение вместо PDF. Но процедура может быть такой же. Сохраните поток в файл и сохраните его в базе данных. Проверить это. Может быть, смогу тебе помочь.
Как сохранить файл pdf в postgresql spring

In this article, we will present how to create a Spring Boot application that uploads a file to the PostgreSQL database. The server application based on REST architecture will use Spring Data JPA for executing queries on the database and MultipartFile interface for handling multi-part requests.
2. Technology
Spring Boot application will use the following technology stack:
- Java 8
- Spring Boot 2
- Spring Data JPA
- PostgreSQL
- Maven 3.6.1
3. Project structure
- FileEntity class that is a data model entity object related to a table in the PostgreSQL database,
- FileResponse is a POJO object used to listing files,
- FileRepository is a Spring Data repository used to save and retrieve files to/from the database,
- FileService is our service that will be calling methods from FileRepository ,
- FilesController used to handle HTTP requests like POST (for uploading files), GET (for listing and downloading files),
- RestExceptionHandler class handles exceptions that could occur when processing requests,
- application.properties is a Spring Boot configuration file used to setup database connection and set file upload size limits,
- pom.xml for project dependencies.
4. REST API for uploading/downloading files
The Spring Boot application will provide a fully REST-ful API for:
- uploading files to PostgreSQL database,
- downloading files from the database,
- retrieving a list of uploaded files.
Spring Boot application will provide the following API endpoints:
URL Method Action /files GET Get list of uploaded files /files POST Upload a single file /files/ GET Download uploaded file Files will be downloaded directly to the database with informations like:
- name of the file,
- size of the file,
- generated UUID to identify the uploaded file,
- file content as BLOB,
- file content type.
5. Configure Spring Boot project
First, we need to create a Spring Boot project using initializer or with IDE like Eclipse, IntelliJ where we can simply create a new Maven project.
Then, we need to add Spring Boot web and Spring JPA starter dependencies to our pom.xml file:
The org.postgresql:postgresql library is used for interactions with the PostgreSQL database.
For the latest versions of this dependecies check the following links:
6. Create Model Entity
Entity objects correspond to database tables. In our project we created a FileEntity class that will be related to the FILES table:
Two fields were marked with special annotations:
- id — @Id , @GeneratedValue(generator = «uuid») , @GenericGenerator(name = «uuid», strategy = «uuid2») — this field will have auto-generated UUID,
- data — @Lob special datatype that informs about storing large objects in the database.
Second POJO class used in model layer is FileResponse :
This object will be used to present a list of files with detailed information about them, such as name, content type, size.
7. Implement data access layer
In our data access layer, we have an interface FileRepository that extends JpaRepository . Thanks to this, we have access to crud methods like save(. ) , getById(. ), delete(. ) etc.
8. Create service for managing files
The FileService class will be responsible for:
- saving uploaded files (transforming MultipartFile object into FileEntity),
- uploading a single file by provided id,
- return a list of uploaded files.
In most cases FileService just calls methods from FileRepository but it is a good place for future business logic.
9. Create a REST controller for handing HTTP requests
The FilesController will be responsible for handling HTTP requests.
This class has been marked with the following annotations:
- @RestController — annotation is used to treat this class as a REST controller,
- @RequestMapping — create a base endpoint to /files URI.
Other annotations used in this class like @GetMapping , @PostMapping and @DeleteMapping — are for mapping HTTP GET, POST and DELETE requests with specific class methods:
HTTP Method Endpoint Method POST /files upload(. ) GET /files list(. ) GET /files/ getFile(. ) 10. Configure JPA, Hibernate and file size upload limits
In the application.properties file we created a several entries:
We used the following properties:
- spring.datasource.url — to define a datasource,
- spring.datasource.username — database username,
- spring.datasource.password — database password,
- spring.jpa.hibernate.ddl-auto can be:
- none — no change is made to the database structure,
- update — Hibernate will change the database according to the given entity structures,
- create — this will creates the database every time on server start,
- create-drop — creates the database and drops it when SessionFactory closes.
11. Create exception handler
The class annotated with @ControllerAdvice is responsible for handling exceptions that may occur during the uploading files process:
We handle just MaxUploadSizeExceededException but this could be extended to some other exceptions as well.
12. Main Spring Boot starting server class
The main Spring Boot application class that starts the server has the following structure:
13. Testing Application API
To run the Spring Boot server use mvn spring-boot:run command or find the generated jar in the /target folder and type java -jar upload-file-to-postgresql-0.0.1-SNAPSHOT.jar .
When everything is correctly configured You should see information about the started server:
Also in the database, there should be a new table called FILES with the following structure:

We will use Postman to make some API requests.
13.1. First, let’s upload some file

In the FILES table a new record appeared:

13.2. Now check a list of uploaded files

13.3. Finally, download the upload file using a provided URL

14. Conclusion
In this tutorial, we presented step by step how to create a Spring Boot application that will upload files to the PostgreSQL database.
As usual, the code used in this tutorial is available in our GitHub repository.