文件下载、预览
点击跳转
文件与byte数组互转
点此跳转
文件下载后,删除目录和文件
点此跳转
以上是参考博客
public void downloadFile(String id, HttpServletResponse res) {
try {
// 获取文件名
String fileName = faSysIgnoreMapper.getFileName(id);
// 下载文件
byte[] bytes = remoteFastdfsService.downloadFile(id).getData();
if (null == bytes){
res.sendError(404, "File not found or empty!");
return;
}
// 生成临时目录路径
String dirPath = FampConfig.PATHCONFIG_TEMPPATH + File.separator + UUID.randomUUID().toString();
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 文件路径
String filePath = dirPath + File.separator + fileName;
File file = new File(filePath);
// byte转文件
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes);
fos.close();
bos.close();
// 下载文件到浏览器
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;
res.reset(); // 非常重要
if (false) { // 在线打开方式 预览
URL u = new URL("file:///" + filePath);
res.setContentType(u.openConnection().getContentType());
res.setHeader("Content-Disposition", "inline; filename=" + file.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
res.setContentType("application/x-msdownload");
res.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
}
OutputStream out = res.getOutputStream();
while ((len = bis.read(bytes)) > 0)
out.write(bytes, 0, len);
bis.close();
out.close();
file.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
实现了pdf的下载和预览、删除,还没有测试图片及其他文件。
什么是数据流
数据流是指所有的数据通信通道
有两类流,InputStream and OutputStream,Java中每一种流的基本功能依赖于它们。
InputStream 用于read,
OutputStream 用于write,
读和写都是相对与内存说的,读就是从其他地方把数据拿进内存,写就是把数据从内存推出去。
这两个都是抽象类,不能直接使用。