Monday 23 December 2019

Spring boot REST: Upload multiple files with input fields


Step 1: Define model class where you map request payload.
public class RequestDto {
    private String description;
    private MultipartFile[] documents;
    .....
    .....
}


Step 2: Map request payload using @ModelAttribute annotation.
@PostMapping("/profile")
public ResponseEntity<responseDto> createProfile(@ModelAttribute RequestDto requestDto) throws IOException {

        MultipartFile[] files = requestDto.getDocuments();

        responseDto responseDto = new responseDto();
        responseDto.setDescription(requestDto.getDescription());

        if (files == null || files.length == 0) {
                return new ResponseEntity<>(responseDto, HttpStatus.CREATED);
        }

        for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                String content = convertToString(file.getInputStream());

                if (responseDto.getFileContent().containsKey(fileName)) {
                        String existingContent = responseDto.getFileContent().get(fileName);
                        content = existingContent + "\n\n" + content;

                }
                responseDto.getFileContent().put(fileName, content);

        }

        return new ResponseEntity<>(responseDto, HttpStatus.CREATED);

}

Find below working application.

Step 1: Create new maven project.

Step 2: Update pom.xml with spring dependencies.


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>springFileUpload</groupId>
        <artifactId>springFileUpload</artifactId>
        <version>1</version>


        <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.6.RELEASE</version>
        </parent>

        <name>springbootApp</name>
        <url>http://maven.apache.org</url>

        <properties>
                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>

        <dependencies>

                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                </dependency>

        </dependencies>
</project>

Step 3: Define model classes.

RequestDto.java
package com.sample.app.model;

import org.springframework.web.multipart.MultipartFile;

public class RequestDto {
        private String description;
        private MultipartFile[] documents;

        public String getDescription() {
                return description;
        }

        public void setDescription(String description) {
                this.description = description;
        }

        public MultipartFile[] getDocuments() {
                return documents;
        }

        public void setDocuments(MultipartFile[] document) {
                this.documents = document;
        }

}


ResponseDto.java
package com.sample.app.model;

import java.util.HashMap;
import java.util.Map;

public class ResponseDto {
        private String description;
        private Map<String, String> fileContent = new HashMap<> ();

        public String getDescription() {
                return description;
        }

        public void setDescription(String description) {
                this.description = description;
        }

        public Map<String, String> getFileContent() {
                return fileContent;
        }

        public void setFileContent(Map<String, String> fileContent) {
                this.fileContent = fileContent;
        }

}

Step 4: Define controller.

FileController.java
package com.sample.app.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sample.app.model.RequestDto;
import com.sample.app.model.ResponseDto;

@RestController
public class FileController {

        @PostMapping("/profile")
        public ResponseEntity<ResponseDto> createProfile(@ModelAttribute RequestDto requestDto) throws IOException {

                MultipartFile[] files = requestDto.getDocuments();

                ResponseDto responseDto = new ResponseDto();
                responseDto.setDescription(requestDto.getDescription());

                if (files == null || files.length == 0) {
                        return new ResponseEntity<>(responseDto, HttpStatus.CREATED);
                }

                for (MultipartFile file : files) {
                        String fileName = file.getOriginalFilename();
                        String content = convertToString(file.getInputStream());

                        if (responseDto.getFileContent().containsKey(fileName)) {
                                String existingContent = responseDto.getFileContent().get(fileName);
                                content = existingContent + "\n\n" + content;

                        }
                        responseDto.getFileContent().put(fileName, content);

                }

                return new ResponseEntity<>(responseDto, HttpStatus.CREATED);

        }

        private static String convertToString(InputStream in) throws IOException {
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) != -1) {
                        result.write(buffer, 0, length);
                }
                return result.toString("UTF-8");
        }
}

Step 5: Define App.java

App.java
package com.sample.app;

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

@SpringBootApplication
public class App {
        public static void main(String[] args) {

                SpringApplication.run(App.class, args);

        }
}

Run App.java.

Hit below request in Postman.
Under Body tab, select form-data.

Add the field description and multiple documents with name ‘documents’.


Once you attached the documents, click on Send button to post the payload. You will receive the description and content of the documents in response.

You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment