文件缓冲流的方式

一下文件,防止没有权限,先复制到临时目录,进行下载,下载完成删除临时文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public void fileDownload(@RequestParam(value = "filePath") String filePath) {
logger.info("download the file param--------filePath:" + filePath);
String fileName = "";
int index = filePath.lastIndexOf("/");
if (index != -1) {
fileName = filePath.substring(index + 1);
}
try {
String username = getLoginUserName();
String user_dir = ConfigUtil.getInstance().getAppformConfig("USERS_DIR_UPLOAD_TEMP");
String tmpDir = user_dir + File.separator + username + File.separator + ".restFileTmp" + File.separator + "." + System.currentTimeMillis();
if (createTmpDir(tmpDir)) {
logger.info(TAG + "创建临时目录文件" + tmpDir);
//移动文件
List<String> params = new ArrayList<>();
params.add("-R");
params.add("-p");
params.add(filePath);
params.add(tmpDir + File.separator);
CmdResult result = client.executeCmd("cp", params, null, "root");

List<String> chmodParams = new ArrayList<>();
chmodParams.add("-R");
chmodParams.add("777");
chmodParams.add(tmpDir + File.separator + fileName);
CmdResult chmodResult = client.executeCmd("chmod", chmodParams, null, "root");
if (result.getExitCode() != 0 || chmodResult.getExitCode() != 0) {
logger.info("move file exit code = " + result.getExitCode() + ";err=" + result.getStderr() + ";out=" + result.getStdout());
logger.info("chmod 777 file exit code = " + chmodResult.getExitCode() + ";err=" + chmodResult.getStderr() + ";out=" + chmodResult.getStdout());
throw new RuntimeException("移动文件异常!");
}
} else {
logger.error(TAG + "创建临时文件错误");
throw new RuntimeException("创建临时文件错误");
}
File tmpFile = new File(tmpDir, fileName);
if (!tmpFile.exists() || !tmpFile.isFile()) {
logger.error(TAG + "文件不存在");
throw new RuntimeException("文件路径错误");
}
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
try (FileInputStream fileInputStream = new FileInputStream(tmpFile);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
logger.error(TAG + "下载文件过程发生错误" + e.getMessage() + e);
throw new RuntimeException("下载文件过程发生错误", e);
}

List<String> params = new ArrayList<>();
params.add("-rf");
params.add(tmpDir);
CmdResult rmResult = client.executeCmd("rm", params, null, "root");
if (rmResult.getExitCode() != 0) {
logger.error(TAG + "rm tmpFile exit code = " + rmResult.getExitCode() + ";err=" + rmResult.getStderr() + ";out=" + rmResult.getStdout());
}
} catch (Exception e) {
logger.error(TAG + e.getMessage() + e);
throw new RuntimeException("下载文件错误!" + e.getMessage());
}
}