返回前端json类
package com.manager.oa.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @Author sms
* @Version V1.0.0
* @Date 2022-08-02
* 响应信息
*/
@Getter
@Setter
public class ResponseEntity<T> {
public ResponseEntity(Boolean success, String code, String msg, T data) {
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
private Boolean success; // 是否成功
private String code;// 响应码
private String msg;// 描述
private T data; // 数据
public final static ResponseEntity<Object> SUCCESS=new ResponseEntity(true,"200","ok",null);
public final static ResponseEntity<Object> FAIL=new ResponseEntity(false,"500","ok",null);
public ResponseEntity(T data) {
this.success = true;
this.code = "200";
this.msg = "ok";
this.data = data;
}
}
文件上传:
1,配置文件上传路径
oa:
staffPhoto: E:\01_program\02_Java EE\staffUpload\staffPhoto\
2,获取配置信息
@Value("${oa.staffPhoto}")
private String staffPhoto; // 读取配置文件注入文件夹路径
3,上传代码
/**
* 员工头像上传
*
* @param file
* @return
* @throws IOException
*/
@PostMapping("/uploadStaffPhoto")
public ResponseEntity<?> uploadStaffPhoto(MultipartFile file) throws IOException {
// 判断文件是否为空
if (file.isEmpty()) {
return new ResponseEntity<>(false, "500", "图片为空", null);
}
// 产生一个32位的唯一字符串
String fileName = UUID.randomUUID().toString().replace("-", "");
log.debug("【系统日志】fileName:->{}", fileName);
String uploadFileName = file.getOriginalFilename();
log.debug("【系统日志】uploadFileName:->{}", uploadFileName);
// 获取文件后缀名
String suffix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
// 获取存放数据库文件名
String DBName = fileName + suffix;
// 获取文件写入路径
String filePath = staffPhoto + fileName + suffix;
// 写入到文件夹
log.debug("【系统日志】filePath:->{}", filePath);
// 写入文件
file.transferTo(new File(filePath));
// 返回前端响应
return new ResponseEntity<>(DBName);
}
文件下载
使用流的方式下载文件
/**
* @param response
* @param filePath 下载的文件路径
* @param fileName 下载后显示的文件名
* @return
*/
public void download(HttpServletResponse response, String filePath, String fileName) {
File file = new File(filePath);
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//使用流的形式下载文件
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
OutputStream os = response.getOutputStream();
) {
byte[] buff = new byte[1024];
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
}
}