Redis缓存操作
文件下载需要保存临时变量
静态常量,在com.swx.easypan.entity.constants
包下的 Constants 类中定义常量
public class Constants { public static final String REDIS_KEY_DOWNLOAD = "easypan:download:"; }
|
从Redis缓存中获取和保存文件下载信息,在RedisComponent 编写获取和保存方法。
RedisComponent@Component("redisComponent") public class RedisComponent {
@Resource private RedisUtils<Object> redisUtils;
public void saveDownloadCode(String code, DownloadFileDTO fileDTO) { redisUtils.setex(Constants.REDIS_KEY_DOWNLOAD + code, fileDTO, Constants.REDIS_KEY_EXPIRE_FIVE_MIN); }
public DownloadFileDTO getDownloadCode(String code) { return (DownloadFileDTO) redisUtils.get(Constants.REDIS_KEY_DOWNLOAD + code); } }
|
创建下载链接
为了防止链接被无限使用,自己创建下载链接,附带code参数,控制链接有效性。
接口信息
定义Service
找到 FileInfoService,定义文件重命名方法
FileInfoService
String createDownloadUrl(String userId, String id);
|
在 FileInfoServiceImpl 中,实现上述方法
FileInfoServiceImpl
@Override public String createDownloadUrl(String userId, String id) { FileInfo fileInfo = getByMultiId(id, userId); if (fileInfo == null) { throw new BizException(ResultCode.PARAM_IS_INVALID); } if (FileFolderTypeEnums.FOLDER.getType().equals(fileInfo.getFolderType())) { throw new BizException(ResultCode.PARAM_IS_INVALID); } String code = StringTools.getRandomString(Constants.LENGTH_50); DownloadFileDTO fileDTO = new DownloadFileDTO(); fileDTO.setCode(code); fileDTO.setFilename(fileInfo.getFilename()); fileDTO.setFilePath(fileInfo.getFilePath()); redisComponent.saveDownloadCode(code, fileDTO); return code; }
|
定义Controller
在 FileInfoController 下定义文件重命名方法。
FileInfoController @GetMapping("/createDownloadUrl/{id}") public Map<String, String> createDownloadUrl(HttpSession session, @PathVariable("id") @NotEmpty String id) { SessionWebUserVO user = (SessionWebUserVO) session.getAttribute(Constants.SESSION_KEY); String code = fileInfoService.createDownloadUrl(user.getId(), id); HashMap<String, String> data = new HashMap<>(); data.put("code", code); return data; }
|
下载文件
接口信息
定义Controller
在 FileInfoController 下定义下载文件方法。根据code从Redis中获取文件信息,然后以字节流的形式返回给前端。
FileInfoController @LoginValidator(validated = false) @GetMapping("/download/{code}") public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable @NotEmpty String code) throws UnsupportedEncodingException { DownloadFileDTO fileDTO = redisComponent.getDownloadCode(code); if (null == fileDTO) { return; } String filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileDTO.getFilePath(); String filename = fileDTO.getFilename(); FileUtils.writeDownloadFile(response, request, filename, filePath); }
|