Springboot中常用的文件上传和下载通用接口
记录下通用的文件上传和下载接口,一般的开发中都是会使用到的,不过写的最简单的版本。文章目录概述概述
·
记录下通用的文件上传和下载接口,一般的开发中都是会使用到的,不过写的最简单的版本。
程序测试
在yml中配置一个文件保存的路径
#保存文件的路径
common:
file: D:/file/
代码响应码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseBean<T> {
private Integer code;
private String msg;
private T data;
}
yaml文件设置上传文件的大小
spring:
servlet:
multipart:
max-file-size: 200MB #单个文件上传大小
max-request-size: 2000MB #连续上传文件大小
测试代码
package cn.yiyiyun.oral.web.controller;
import cn.yiyiyun.response.ResponseBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/api/common")
@Api(tags = "通用的文件上传和下载接口")
@Slf4j
public class FileCommonController {
@Value("${common.file}")
private String path;
@SneakyThrows
@GetMapping("/downloadExport")
@ApiOperation(value = "下载导出的文件")
public void downloadExport(String fileName, HttpServletResponse response) {
//response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
// 文件名称乱码的问题
response.addHeader("Content-Disposition","attachment;fileName=" +
new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
File file = new File(path + fileName);
ServletOutputStream outputStream;
byte[] array;
try {
outputStream = response.getOutputStream();
array = FileUtils.readFileToByteArray(file);
outputStream.write(array);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
return;
}
}
/**
* 通用上传单个文件请求
*/
@SneakyThrows
@PostMapping("/uploadSingleFile")
@ApiOperation(value = "上传单个文件")
public ResponseBean<?> uploadSingleFile(MultipartFile file) {
//新文件名
String newFileName = file.getOriginalFilename();
//若文件夹不存在,则创建文件夹
File parentFile = new File(path + "test.txt").getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 保存文件
file.transferTo(new File(path + newFileName));
log.info("接收文件:" + newFileName);
//返回信息
return new ResponseBean<>(200, "上传成功", newFileName);
}
}
swagger测试
本文小结
本文写了一个最简单的文件上传和下载接口,可以在这个基础上进行扩展。
更多推荐
已为社区贡献28条内容
所有评论(0)