博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot File Upload / Download Rest API Example
阅读量:6983 次
发布时间:2019-06-27

本文共 6114 字,大约阅读时间需要 20 分钟。

Uploading and downloading files are very common tasks for which developers need to write code in their applications.

In this article, You’ll learn how to upload and download files in a RESTful spring boot web service.

We’ll first build the REST APIs for uploading and downloading files, and then test those APIs using Postman. We’ll also write front-end code in javascript to upload files.

Following is the final version of our application -

Spring Boot File Upload and Download AJAX Rest API Web Service

All right! Let’s get started.

Creating the Application

Let’s generate our application using . Fire up your terminal, and type the following command to generate the app -

$ spring init --name=file-demo --dependencies=web file-demoUsing service at https://start.spring.ioProject extracted to '/Users/rajeevkumarsingh/spring-boot/file-demo'

You may also generate the application through  web tool by following the instructions below -

  1. Open 
  2. Enter file-demo in the “Artifact” field.
  3. Add Web in the dependencies section.
  4. Click Generate Project to download the application.

That’s it! You may now unzip the downloaded application archive and import it into your favorite IDE.

 

Configuring Server and File Storage Properties

First thing First! Let’s configure our Spring Boot application to enable Multipart file uploads, and define the maximum file size that can be uploaded. We’ll also configure the directory into which all the uploaded files will be stored.

Open src/main/resources/application.properties file, and add the following properties to it -

## MULTIPART (MultipartProperties)# Enable multipart uploadsspring.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=200MB # Max Request Size spring.servlet.multipart.max-request-size=215MB ## File Storage Properties # All files uploaded through the REST API will be stored in this directory file.upload-dir=./uploads

You may change the above properties depending on your project requirements.

Automatically binding properties to a POJO class

Spring Boot has an awesome feature called  using which you can automatically bind the properties defined in the application.properties file to a POJO class.

Let’s define a POJO class called FileStorageProperties inside com.example.filedemo.property package to bind all the file storage properties -

package com.example.filedemo.property; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "file") public class FileStorageProperties { private String uploadDir; public String getUploadDir() { return uploadDir; } public void setUploadDir(String uploadDir) { this.uploadDir = uploadDir; } }

The @ConfigurationProperties(prefix = "file") annotation does its job on application startup and binds all the properties with prefix file to the corresponding fields of the POJO class.

If you define additional file properties in future, you may simply add a corresponding field in the above class, and spring boot will automatically bind the field with the property value.

Enable Configuration Properties

Now, To enable the ConfigurationProperties feature, you need to add annotation to any configuration class.

Open the main class src/main/java/com/example/filedemo/FileDemoApplication.java, and add the @EnableConfigurationProperties annotation to it like so -

package com.example.filedemo; import com.example.filedemo.property.FileStorageProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties({ FileStorageProperties.class }) public class FileDemoApplication { public static void main(String[] args) { SpringApplication.run(FileDemoApplication.class, args); } }

Writing APIs for File Upload and Download

Let’s now write the REST APIs for uploading and downloading files. Create a new controller class called FileController inside com.example.filedemo.controller package.

Here is the complete code for FileController -

package com.example.filedemo.controller; import com.example.filedemo.payload.UploadFileResponse; import com.example.filedemo.service.FileStorageService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @RestController public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileStorageService fileStorageService; @PostMapping("/uploadFile") public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) { String fileName = fileStorageService.storeFile(file); String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/downloadFile/") .path(fileName) .toUriString(); return new UploadFileResponse(fileName, fileDownloadUri, file.getContentType(), file.getSize()); } @PostMapping("/uploadMultipleFiles") public List
uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) { return Arrays.asList(files) .stream() .map(file -> uploadFile(file)) .collect(Collectors.toList()); } @GetMapping("/downloadFile/{fileName:.+}") public ResponseEntity
downloadFile(@PathVariable String fileName, HttpServletRequest request) { // Load file as Resource Resource resource = fileStorageService.loadFileAsResource(fileName); // Try to determine file's content type String contentType = null; try { contentType = request.getServletContext(

转载地址:http://hztpl.baihongyu.com/

你可能感兴趣的文章
阿里云将增设马来西亚数据中心 中国技术获赞
查看>>
与Netflix合作 美电视运营商推出4K频道
查看>>
Struts2中的Action
查看>>
Balluff推出刀具识别系统
查看>>
怎么写ERP实施方案?
查看>>
Shadow Brokers扬言兜售新漏洞攻击工具
查看>>
低照度监控前景广阔 企业展开激烈角逐
查看>>
美国支付巨头Verifone遭遇网络攻击
查看>>
开平推进智慧城市等领域信息化建设及公共数据资源共享
查看>>
宜兴电信成功跨界合作开拓农村物联网市场
查看>>
Oracle业务适合用PostgreSQL去O的一些评判标准
查看>>
多个常见代码设计缺陷
查看>>
今年光伏市场规模可达30GW 分布式有望占据三分江山
查看>>
因新漏洞问题 Firefox 49发布时间将延期一周
查看>>
WLAN产品形态之分层架构
查看>>
《敏捷可执行需求说明 Scrum提炼及实现技术》—— 1.2 识别不确定性的影响
查看>>
Chrome 隐藏 SSL 证书信息 禁止禁用 DRM
查看>>
《Windows Server 2012 Hyper-V虚拟化管理实践》——3.2 Hyper-V主机日常管理
查看>>
《C语言编程魔法书:基于C11标准》——第一篇 预备知识篇 第1章 C魔法概览1.1 例说编程语言...
查看>>
《IPv6安全》——1.7 推荐读物和资料
查看>>