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

图片预览

@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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值