[java]文件上传下载删除与图片预览

时间:2021-09-10 16:00:50

图片预览

    @GetMapping("/image")
@ResponseBody
public Result image(@RequestParam("imageName") String imageName, HttpServletResponse response) { // 判断图片是否存在
int result = HbaseUtil.fileIsExist(Constant.tableName, imageName);
if (result == -1) {
return ResultUtil.fileNotFoundError();
} else{
InputStream in = null;
ServletOutputStream sos = null;
try {
FunctionSelect.fileGetF(Constant.tableName, imageName, Constant.downloadTmpDir);
File file = new File(Constant.downloadTmpDir + "/" + imageName);
in = new FileInputStream(file);
sos = response.getOutputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {
// 写出
sos.write(b);
}
//刷新
sos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭文件读取流,输出流
in.close();
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

文件下载

本质和图片预览一样,都是输出字节流,不过文件下载加了一个强制下载。

    /**
* 1. 判断文件是否存在 2.设置下载文件
*
* @param filename
* @param response
* @return
*/
@GetMapping("/download")
@ResponseBody
public Result download(@RequestParam("filename") String filename, HttpServletResponse response) {
int result = HbaseUtil.fileIsExist(Constant.tableName, filename);
if (result == -1) {
return ResultUtil.fileNotFoundError();
} else {
try {
// 文件download到服务器上
// TODO: 2020/12/22 这里需要控制文件数量或者总文件夹大小 以便于做进一步的缓存
// todo: 需要做一个定时任务,定期删除文件夹中超过30天的文件。(done)
FunctionSelect.fileGetF(Constant.tableName, filename, Constant.downloadTmpDir); // 根据路径和文件名创建文件
// TODO: 2020/12/22 此处逻辑需要修改 去掉lob文件夹 修改之前的代码(Completed)
File file = new File(Constant.downloadTmpDir + "/" + filename); //File file = new File(realPath , fileName);
if (file.exists()) {
// 设置强制下载不打开
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + filename);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.unknownError();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.unknownError();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.unknownError();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.unknownError();
}
}
return null;
}