一、将文件发返回给前端
Controller:
@ApiOperation(value = "IO流返回给前端")
@GetMapping("fileView")
public void fileView(@ApiParam(value = "文件路径", required = true) @RequestParam String fileUrl, HttpServletResponse response) {
fileService.fileView(fileUrl, response);
}
Service:
/**
* 以IO流的形式返回给前端
*
* @param fileUrl 文件路径
* @param response resp
*/
public void fileView(String fileUrl, HttpServletResponse response) {
// 读取文件名 例:yyds.jpg
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
try (FileInputStream inputStream = new FileInputStream(fileUrl);
OutputStream outputStream = response.getOutputStream()) {
byte[] data = new byte[1024];
// 全文件类型(传什么文件返回什么文件流)
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Accept-Ranges", "bytes");
int read;
while ((read = inputStream.read(data)) != -1) {
outputStream.write(data, 0, read);
}
// 将缓存区数据进行输出
outputStream.flush();
} catch (IOException e) {
log.error("失败", e);
throw new Exception("exception");
}
}
二、将前端的文件信息返回后端处理
pring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件,例如:
先写好一个配置在application.yml,以备使用
files:
upload:
path: F:/后台管理系统/files/
Controller
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
//文件磁盘路径
@Value("${files.upload.path}")
private String fileUploadPath;
@PostMapping("/upload")
public Result upload(@RequestParam MultipartFile file) throws IOException {
//获取文件原始名称
String originalFilename = file.getOriginalFilename();
//获取文件的类型
String type = FileUtil.extName(originalFilename);
log.info("文件类型是:" + type);
//获取文件大小
long size = file.getSize();
//获取文件
File uploadParentFile = new File(fileUploadPath);
//判断文件目录是否存在
if(!uploadParentFile.exists()) {
//如果不存在就创建文件夹
uploadParentFile.mkdirs();
}
//定义一个文件唯一标识码(UUID)
String uuid = UUID.randomUUID().toString();
File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + type);
//将临时文件转存到指定磁盘位置
file.transferTo(uploadFile);
return Result.success("");
}
}
即可完成