Spring Boot REST API如何实现接收任意扩展名文件并返回加密后文件
实现方案
1. 前置说明
Spring Boot 自带文件上传处理能力,引入spring-boot-starter-web依赖即可直接使用,无需额外引入其他依赖。
2. 完整控制器实现
import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @RestController @RequestMapping(value = "/encode") public class EncodeController { @PostMapping("/v1") public ResponseEntity<byte[]> encodeFile(@RequestParam("file") MultipartFile uploadFile) throws Exception { // 1. 调用你实现的加密逻辑,返回加密后的文件 File encodedFile = encode(uploadFile); // 2. 读取加密后的文件为字节数组 ByteArrayOutputStream baos = new ByteArrayOutputStream(); try(FileInputStream fis = new FileInputStream(encodedFile)){ byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { baos.write(buffer, 0, len); } } byte[] encodedBytes = baos.toByteArray(); // 3. 设置响应头,触发浏览器自动下载,文件名和扩展名可自定义 String downloadFileName = "encrypted_" + uploadFile.getOriginalFilename() + ".enc"; // 后缀按加密后的格式自定义 String encodedFileName = URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8); // 处理中文文件名乱码 HttpHeaders headers = new HttpHeaders(); // 标记响应为附件,浏览器会自动触发下载 headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName); // 通用二进制流类型,适配任意扩展名文件 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 4. 返回响应 return ResponseEntity.ok() .headers(headers) .body(encodedBytes); } // 自行实现加密逻辑,入参可按需求调整 private File encode(MultipartFile uploadFile) throws Exception{ // 加密业务逻辑写在这里 return null; } }
3. 可选配置(调整文件大小限制)
默认Spring Boot最大支持单个文件1MB、单次请求总大小10MB,如需上传更大文件,在application.properties中添加配置即可:
# 单个文件最大大小 spring.servlet.multipart.max-file-size=100MB # 单次请求所有文件总最大大小 spring.servlet.multipart.max-request-size=200MB
4. 前端调用要求
上传接口必须用multipart/form-data类型提交,基础表单示例:
<form method="post" enctype="multipart/form-data" action="/encode/v1"> <input type="file" name="file" /> <button type="submit">加密文件</button> </form>
关键逻辑说明
- 接收文件:用
MultipartFile接口接收任意类型的上传文件,可通过getOriginalFilename()拿到原始文件名、getInputStream()拿到文件流,无需提前限制扩展名。 - 触发下载:设置
Content-Disposition响应头为attachment类型、指定下载文件名,浏览器就会自动弹出下载框,不会直接展示内容。 - 自定义扩展名:返回的下载文件名可以任意指定后缀,和原始文件扩展名无关,满足返回任意扩展名加密文件的需求。
内容的提问来源于stack exchange,提问作者Pedro Accorsi
相关产品推荐
相关产品推荐

