需求
由于项目中需要用户上传文件和下载文件,则后端中需要写相应的接口
实现
下载功能
- 下载需要传入
HttpServletResponse
,用于设置header信息 - 可以同时传入其他信息
@ApiOperation("下载文件")
@GetMapping("/download/{id}")
public Result download(@PathVariable Integer id, HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
TimeInterval timer = DateUtil.timer();
String uploadFilePath = modulemdService.download(fileName, id);
File file = new File(uploadFilePath);
response.reset();
// response.setContentType("application/octet-stream");
response.setContentType("application/json;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] readBytes = FileUtil.readBytes(file);//读取文件
OutputStream os = response.getOutputStream();//获取输出流
os.write(readBytes);// 输出文件
return Result.success("花费时间"+timer.interval()+"ms");
}
上传功能
- 设置parma参数为file,传入类型为
MultipartFile
,不能传入requestbody参数 - new一个File对象,参数为储存在服务器的路径:
File fileTempObj = new File(uploadFilePath + "/" + fileName);
- 使用hutool工具类写入文件,保存在服务器地址:
FileUtil.writeBytes(file.getBytes(), fileTempObj);
@PostMapping("/uploadFile")
public String fileUpload(@RequestParam("file") MultipartFile file) throws JSONException {
JSONObject result = new JSONObject();
if (file.isEmpty()) {
result.append("error", "空文件!");
return result.toString();
}
// 文件名
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传文件名称为:"+fileName+", 后缀名为:"+suffixName);
File fileTempObj = new File(uploadFilePath + "/" + fileName);
// 检测目录是否存在
if (!fileTempObj.getParentFile().exists()) {
fileTempObj.getParentFile().mkdirs();
}
// 使用文件名称检测文件是否已经存在
if (fileTempObj.exists()) {
result.put("error", "文件已经存在!");
return result.toString();
}
try {
// 写入文件:方式1
// file.transferTo(fileTempObj);
// 写入文件:方式2
FileUtil.writeBytes(file.getBytes(), fileTempObj);
} catch (Exception e) {
System.out.println("错误信息:"+e.getMessage());
result.append("error", e.getMessage());
return result.toString();
}
result.append("success", "文件上传成功!");
return result.toString();
}