在现代Web应用中,文件管理是一个非常重要的功能。Spring Boot作为Java开发领域的热门框架,提供了丰富的工具和API来简化文件管理的操作。本文将详细介绍如何使用Spring Boot 3进行文件的上传、下载、预览、查询与删除操作,并提供一个完整的示例代码。
文件预览支持多格式!!!(文档/图片/视频/音频.....)
废话不多说,直接开撸。
1.pom.xml 和 yml
<!--File 文件Util-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
<!--StringUtils-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
# 自定义信息
customInfo:
# 获取文件存放信息路径
file:
storagePath: "/static/file/"
2.Util 工具类
public class ToolUtil {
/**
* 判断权限是否存在
*/
public static Boolean bollPurviewTool(String[] list, String str){
String[] list2 = str.split(",");
for (String item:list) {
for (String item2:list2) {
if (item.equals(item2)){
return true;
}
}
}
return false;
}
/**
* 获取当前系统路径的上一级
*/
public static String currentParentPath(){
String currentDirectory = System.getProperty("user.dir");
File file = new File(currentDirectory);
String parentDirectory = file.getParent();
return parentDirectory;
}
}
3.FileController
备注:@RateLimit @VerifySign 注解是我的自定义注解你可以删除,
JwtRedistService 是我的权限判定方法,你可以删除
JwtInfo 是我的token令牌涉及相关方法 ,这些方法你都可以去掉
import com.portalwebsiteservice.demos.web.Dto.JwtInfo;
import com.portalwebsiteservice.demos.web.Dto.Result;
import com.portalwebsiteservice.demos.web.Enum.PurviewEnum;
import com.portalwebsiteservice.demos.web.Enum.ResultEnum;
import com.portalwebsiteservice.demos.web.Service.FileService;
import com.portalwebsiteservice.demos.web.Service.JwtRedistService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import static com.portalwebsiteservice.demos.web.Util.ToolUtil.bollPurviewTool;
/**
* 文件管理
*/
@RestController
@RequestMapping("/file")
public class FileController {
@Resource
private FileService fileService;
@Resource
private JwtRedistService jwtRedistService;
/**
* 文件上传
*/
@PostMapping("/upload")
public Result uploadFile(@RequestParam("file") MultipartFile file) {
Result result = new Result();
if (file==null) {
result.setCode(400);
result.setMsg("至少选择一个文件上传!");
return result;
}else {
return fileService.uploadFileService(file);
}
}
/**
* 文件下载
*/
@RateLimit
@GetMapping("/download/{id}")
public ResponseEntity<FileSystemResource> downloadFile(@PathVariable String id,@RequestHeader("Authorization") String token) {
JwtInfo jwtInfo = jwtRedistService.getUserInfo(token);
return fileService.downloadFileService(jwtInfo,id);
}
/**
* 文件预览
*/
@RateLimit
@GetMapping("/visit/{path}")
public void downloadFile(@PathVariable String path, HttpServletResponse response) {
fileService.viewFile(path,response);
}
/**
* 文件查询 (管理端)
*/
@RateLimit
@VerifySign
@GetMapping("/queryAll")
public Result queryFileAll(@RequestParam Integer page,@RequestParam Integer limit, @RequestParam(required = false) String keyword, @RequestHeader("Authorization") String token){
Result result = new Result();
try {
JwtInfo jwtInfo = jwtRedistService.getUserInfo(token);
//需要超级管理员
if (bollPurviewTool(jwtInfo.getPurview(), PurviewEnum.ADMINISTRATOR.getValue())){
return fileService.queryAllFileService(jwtInfo,keyword,page,limit);
}else {
result.setCode(ResultEnum.ADMIN.getCode());
result.setMsg(ResultEnum.ADMIN.getData());
}
}catch (Exception e){
result.setCode(ResultEnum.UNKNOWNERROR.getCode());
result.setMsg(ResultEnum.FORBIDDEN.getData());
result.setData(e.getCause());
}
return result;
}
/**
* 文件查询 (服务端)
*/
@RateLimit
@GetMapping("/query")
public Result queryFile(@RequestParam String id, @RequestHeader("Authorization") String token){
Result result = new Result();
try {
JwtInfo jwtInfo = jwtRedistService.getUserInfo(token);
return fileService.queryFileService(jwtInfo,id);
}catch (Exception e){
result.setCode(ResultEnum.UNKNOWNERROR.getCode());
result.setMsg(ResultEnum.FORBIDDEN.getData());
result.setData(e.getCause());
}
return result;
}
/**
* 文件删除
*/
@VerifySign
@RateLimit(limit = 5)
@PostMapping("/delete")
public Result deleteFile(List<String> ids ,@RequestHeader("Authorization") String token) {
Result result = new Result();
try {
JwtInfo jwtInfo = jwtRedistService.getUserInfo(token);
return fileService.deleteFileService(jwtInfo,ids);
}catch (Exception e){
result.setCode(ResultEnum.UNKNOWNERROR.getCode());
result.setMsg(ResultEnum.FORBIDDEN.getData());
result.setData(e.getCause());
}
return result;
}
}
4.Entity 实体Dao
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName(value = "sys_file",autoResultMap = true)
public class File {
/**
* id
*/
private String id;
/**
* 文件名称
*/
private String name;
/**
* 文件路径
*/
private String path;
/**
* 文件类型
*/
private String type;
/**
* 文件大小
*/
private String size;
/**
* 文件访问权限
*/
private String purview;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.portalwebsiteservice.demos.web.Entity.File;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface FileDao extends BaseMapper<File> {
}
5.FileServiceImpl 和 FileService 业务操作
备注:PurviewEnum 是我定义权限的封装枚举类,涉及该方法是你可以直接删除
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.portalwebsiteservice.demos.web.Dao.FileDao;
import com.portalwebsiteservice.demos.web.Dto.JwtInfo;
import com.portalwebsiteservice.demos.web.Dto.Result;
import com.portalwebsiteservice.demos.web.Entity.File;
import com.portalwebsiteservice.demos.web.Enum.PurviewEnum;
import com.portalwebsiteservice.demos.web.Service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import static com.portalwebsiteservice.demos.web.Util.ToolUtil.bollPurviewTool;
import static com.portalwebsiteservice.demos.web.Util.ToolUtil.currentParentPath;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private FileDao fileDao;
@Value("${customInfo.file.storagePath}")
private String storagePath;
/**
* 文件上传
*/
@Override
public Result uploadFileService(MultipartFile file) {
Result result = new Result();
File fileMap = new File();
String currentPath = currentParentPath();
//创建时间
fileMap.setCreateTime(new Date());
fileMap.setUpdateTime(new Date());
fileMap.setPurview(PurviewEnum.ORDINARY.getValue());
//用户ID
String uId = UUID.randomUUID().toString().replace("-","");
fileMap.setId(uId);
//文件name
String fileName = file.getOriginalFilename();
fileMap.setName(fileName);
//文件大小
String fileSize = String.valueOf(file.getSize());
fileMap.setSize(fileSize);
//文件类型
String fileType = null;
if (fileName != null) {
fileType = fileName.substring(fileName.lastIndexOf(".")+1);
}
fileMap.setType(fileType);
//文件path
String filePathName = uId + "." + fileType;
fileMap.setPath(filePathName);
//拼接文件存放地址
java.io.File dest=new java.io.File(currentPath+storagePath + filePathName);
//判断文件路径是否存在 如果不存在就创建文件路径
if (dest.getParentFile().exists()) dest.getParentFile().mkdirs();
//文件保存
try {
FileUtil.writeBytes(file.getBytes(), currentPath+storagePath + filePathName);
fileDao.insert(fileMap);
result.setData(fileMap);
result.setMsg("上传成功");
} catch (IOException e) {
e.fillInStackTrace();
result.setData(e);
}
return result;
}
/**
* 文件下载
*/
@Override
public ResponseEntity<FileSystemResource> downloadFileService(JwtInfo jwtInfo, String id) {
LambdaQueryWrapper<File> lqw = new LambdaQueryWrapper<>();
lqw.eq(File::getId,id);
if (jwtInfo.getPass()) {
String[] purviewList = jwtInfo.getPurview();
lqw.in(File::getPurview, Arrays.asList(purviewList));
} else {
lqw.eq(File::getPurview, PurviewEnum.ORDINARY.getValue());
}
File fileMap = fileDao.selectOne(lqw);
//设置文件完整路径
String currentPath = currentParentPath();
// 设置响应头
HttpHeaders headers = new HttpHeaders();
if (fileMap!=null && jwtInfo.getPass()){
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+fileMap.getPath());
try {
// 加载文件作为资源
java.io.File file = new java.io.File(currentPath+fileMap.getPath());
FileSystemResource resource = new FileSystemResource(file);
// 返回文件内容
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}catch (Exception e){
return ResponseEntity.ok()
.headers(headers)
.contentLength(0)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(null);
}
}else {
return ResponseEntity.ok()
.headers(headers)
.contentLength(0)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(null);
}
}
/**
* 文件预览
*/
@Override
public void viewFile(String path, HttpServletResponse response){
String currentPath = currentParentPath() + storagePath + path;
if (!currentPath.equals(currentParentPath())) {
try (ServletOutputStream os = response.getOutputStream()) {
Path filePath = Paths.get(currentPath);
byte[] b = Files.readAllBytes(filePath);
os.write(b);
} catch (IOException e) {
e.fillInStackTrace();
}
}
}
/**
* 文件查询(管理端)
*/
@Override
public Result queryAllFileService(JwtInfo jwtInfo, String keyword, Integer page, Integer limit) {
Result result = new Result();
try {
if (jwtInfo.getPass()){
if (bollPurviewTool(jwtInfo.getPurview(), PurviewEnum.ADMINISTRATOR.getValue())){
if (keyword!=null && !keyword.isEmpty()){
LambdaQueryWrapper<File> lqw = new LambdaQueryWrapper<>();
lqw.like(File::getId, keyword).or()
.like(File::getName, keyword).or()
.like(File::getType, keyword).or()
.like(File::getPath, keyword);
Page<File> pages = new Page<>(page, limit);
IPage<File> iPage = fileDao.selectPage(pages,lqw);
result.setMsg("模糊查询成功!");
result.setData(iPage);
}else {
Page<File> pages = new Page<>(page, limit);
IPage<File> iPage = fileDao.selectPage(pages,null);
result.setMsg("文件信息查询成功!");
result.setData(iPage);
}
}else {
result.setMsg("暂无操作权限!");
result.setCode(400);
}
}else {
result.setMsg("token令牌过期!");
result.setCode(400);
}
}catch (Exception e){
result.setData(e.getCause());
result.setMsg("程序报错!");
result.setCode(500);
}
return result;
}
/**
* 文件查询(服务端)
*/
@Override
public Result queryFileService(JwtInfo jwtInfo, String id) {
Result result = new Result();
try {
LambdaQueryWrapper<File> lqw = new LambdaQueryWrapper<>();
lqw.eq(File::getId,id);
if (jwtInfo.getPass()) {
String[] purviewList = jwtInfo.getPurview();
lqw.in(File::getPurview, Arrays.asList(purviewList));
} else {
lqw.eq(File::getPurview, PurviewEnum.ORDINARY.getValue());
}
File file = fileDao.selectOne(lqw);
result.setMsg("文件信息查询成功!");
result.setData(file);
}catch (Exception e){
result.setData(e.getCause());
result.setMsg("程序报错!");
result.setCode(500);
}
return result;
}
/**
* 文件删除
*/
@Override
public Result deleteFileService(JwtInfo jwtInfo, List<String> ids) {
Result result = new Result();
if (jwtInfo.getPass()){
int res = fileDao.deleteBatchIds(ids);
if (res > 0){
result.setMsg("文件删除成功!");
}else {
result.setMsg("文件删除失败!");
result.setCode(400);
}
}else {
result.setMsg("token令牌过期!");
result.setCode(400);
}
return result;
}
}
以上就是完整代码!!有代码问题可以咨询小编。