一、文件上传
创建数据库表
Files
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("sys_file")
public class Files {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private String type;
private Long size;
private String url;
private Boolean isDelete;
private Boolean enable;
}
FileMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springboot.entity.Files;
public interface FileMapper extends BaseMapper<Files> {
}
FileController
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${files.upload.path}")
private String fileUploadPath;
@Resource
private FileMapper fileMapper;
/**
* 文件上传接口
*
* @param file 前端传过来的文件
* @return
*/
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String type = FileUtil.extName(originalFilename);
Long size = file.getSize();
//先存储数据库
File uploadParentFile = new File(fileUploadPath);
//判断配置文件目录是否存在,若不存在则新创建一个文件目录
if (!uploadParentFile.exists()) {
uploadParentFile.mkdirs();
}
//定义一个文件唯一的标识码
String uuid = IdUtil.fastSimpleUUID();
String fileUUID = uuid+StrUtil.DOT+type;
//文件加后缀 StrUtil.DOT + type
File uploadFile = new File(fileUploadPath + fileUUID);
//把获取到的文件存储到磁盘目录中
file.transferTo(uploadFile);
//文件路径
String url = "http://localhost:9090/file/" + fileUUID;
//存储到数据库
Files saveFile = new Files();
saveFile.setName(originalFilename);
saveFile.setType(type);
//将size转成kb
saveFile.setSize(size/1024);
saveFile.setUrl(url);
fileMapper.insert(saveFile);
return url;
}
}
二、文件下载
FileController
/**
* 文件下载路径 "http://localhost:9090/file/{fileUUID}"
* @param fileUUID
* @param response
* @throws IOException
* */
@GetMapping("/{fileUUID}")
public void download(@PathVariable String fileUUID, HttpServletResponse response) throws Exception{
//根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("application/octet-stream");
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}