Wednesday, 24 March 2021

Spring boot: Upload and download images

In this post, I am going to explain how to download and upload images using spring boot application.

 

Download image

@ApiOperation(value = "Get given image", notes = "This API will get the image")
@GetMapping(value = "by-name/{name}", produces = { MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE,
		MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<Resource> image(
		@ApiParam(name = "name", value = "Image name.", required = true) @PathVariable("name") String name)
		throws IOException {
	final ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get(IMAGES_PATH + name)));
	return ResponseEntity.status(HttpStatus.OK).contentLength(inputStream.contentLength()).body(inputStream);
}

 

Upload images

@ApiOperation(value = "Upload the image", notes = "This API will upload the image")
@PostMapping("upload")
public ResponseEntity<String> uploadFiles(@ModelAttribute ImageUploadDto requestDto) throws IOException {

	System.out.println(requestDto.getDescription());
	MultipartFile[] multiPartFiles = requestDto.getDocuments();

	for (MultipartFile multiPartFile : multiPartFiles) {
		//String name = multiPartFile.getName();
		String originalFileName = multiPartFile.getOriginalFilename();
		

		try (InputStream is = multiPartFile.getInputStream();
				OutputStream os = new FileOutputStream(IMAGES_PATH + originalFileName)) {
			IOUtils.copy(is, os);
		}

	}

	return ResponseEntity.status(HttpStatus.CREATED).body("Success");

}

Follow below step-by-step prodecure to build complete working application.

 

Step 1: Create new maven project 'send-and-receive-image'.

 

Step 2: Update pom.xml with maven 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>com.sample.app</groupId>
	<artifactId>send-and-receive-image</artifactId>
	<version>1</version>

	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>

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

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>


		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.4</version>
		</dependency>


	</dependencies>
</project>


Step 3: create new package ‘com.sample.app.dto’ and define ImageUploadDto class.

 

ImageUploadDto.java

package com.sample.app.dto;

import org.springframework.web.multipart.MultipartFile;

public class ImageUploadDto {
	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[] documents) {
		this.documents = documents;
	}

}


Step 4: Create a package ‘com.sample.app.config’ and define SwaggerConfig class.

 

SwaggerConfig.java

package com.sample.app.config;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Component
@EnableAutoConfiguration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket userApi() {

		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().paths(PathSelectors.any())
				.apis(RequestHandlerSelectors.basePackage("com.sample.app.controller")).build();
	}

	private ApiInfo apiInfo() {

		return new ApiInfoBuilder().title("Query builder").description("Query builder using spring specification")
				.version("2.0").build();
	}
}


Step 5:Create a package ‘com.sample.app.controller’ and define ImageController class.

 

ImageController.java

package com.sample.app.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sample.app.dto.ImageUploadDto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/v1/images/")
@Api(tags = "Image controller", description = "This section contains image related APIs")
public class ImageController {

	private static final String IMAGES_PATH = "/Users/Shared/images/";

	@ApiOperation(value = "Get given image", notes = "This API will get the image")
	@GetMapping(value = "by-name/{name}", produces = { MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE,
			MediaType.IMAGE_PNG_VALUE })
	public ResponseEntity<Resource> image(
			@ApiParam(name = "name", value = "Image name.", required = true) @PathVariable("name") String name)
			throws IOException {
		final ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get(IMAGES_PATH + name)));
		return ResponseEntity.status(HttpStatus.OK).contentLength(inputStream.contentLength()).body(inputStream);
	}

	@ApiOperation(value = "Upload the image", notes = "This API will upload the image")
	@PostMapping("upload")
	public ResponseEntity<String> uploadFiles(@ModelAttribute ImageUploadDto requestDto) throws IOException {

		System.out.println(requestDto.getDescription());
		MultipartFile[] multiPartFiles = requestDto.getDocuments();

		for (MultipartFile multiPartFile : multiPartFiles) {
			// String name = multiPartFile.getName();
			String originalFileName = multiPartFile.getOriginalFilename();

			try (InputStream is = multiPartFile.getInputStream();
					OutputStream os = new FileOutputStream(IMAGES_PATH + originalFileName)) {
				IOUtils.copy(is, os);
			}

		}

		return ResponseEntity.status(HttpStatus.CREATED).body("Success");

	}

}


Step 6: Define main application class.

 

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);

	}
}


Total project structure looks like below.




Run App.java.

 

Upload files using postman

Method: Post

API: http://localhost:8080/v1/images/upload

Go to Body section and select form-data.

 

Add description key with value 'Test uploading' and add multiple files using the key ‘documents’.


Click on Send button.

 

You will see a response code of 201 and the file gets created successfully.

 

Now use the GET api to retrieve the images stored in disk location ‘/Users/Shared/images/’.

 

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/rest/send-and-receive-image



 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment