一、前端部分
前端下载按钮:
<el-button @click="download(scope.row)"
icon="el-icon-download"
type="text"
size="small">下载
</el-button>
对应按键方法:
//下载
download(row) {
this.$confirm("确定下载?", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
downloadJsMethod(row).then(res => {
let contentDisposition = res.headers['content-disposition']
let pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
let result = pattern.exec(contentDisposition)
// 使用decodeURI对名字进行解码
let fileName = decodeURI(result[1])
// 下载文件
downloadFileByBlob(res.data, fileName);
});
})
},
对应JS方法downloadJsMethod:
export const downloadJsMethod= (row) => {
return request({
url: '/api/download',
method: 'post',
responseType: 'blob',
data: data
})
}
二、后端部分
Java后端Controller接收方法:
/**
* 下载
*/
@ApiLog("下载")
@PostMapping("/download")
public void download(HttpServletResponse response, @RequestBody JSONObject json) {
try {
//JSONObject参数是为了接收前端传过来的对象类型,具体可以自己定义
downloadService.download(response,json);
} catch (Exception e) {
throw new ServiceException("下载失败,请检查");
}
}
Java后端Service处理方法:
@Override
public void download(HttpServletResponse response, JSONObject object) {
String filePath = object.getFilePath();//获取文件路径
String downloadName = object.getFileName();//下载的文件名称
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);//获取文件名称
try (SSHTools sshTools = SSHTools.getInstance(下载的服务器IP, 下载的服务器端口, 下载的服务器用户名, 下载的服务器密码);) {
InputStream inputStream = sshTools.sshSftpDownload(fileName, filePath.replace(fileName, ""));
File file = inputStreamToFile(inputStream);
FileInputStream fileInputStream = new FileInputStream(file);
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(downloadName , "UTF-8"));
// 告知浏览器文件的大小
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
log.error("下载失败", e);
throw new ServiceException("下载失败:" + e.getMessage());
}
}
附SSHTools 工具类方法:
public class SSHTools implements AutoCloseable {
private Session session;
private InputStream inputStream;
public static SSHTools getInstance(String hostIp, Integer hostPort, String user, String password) {
log.info("SSHTools new instance by password. address:" + user + "@" + hostIp);
SSHTools sshTools = new SSHTools();
sshTools.passwordAuthentication(hostIp, hostPort, user, password);
return sshTools;
}
public InputStream sshSftpDownload(String fileName, String path) {
Channel channel = null;
try {
//创建sftp通信通道
channel = (Channel) session.openChannel("sftp");
channel.connect(1000);
ChannelSftp sftp = (ChannelSftp) channel;
//进入服务器指定的文件夹
sftp.cd(path);
//下载
inputStream = sftp.get(fileName);
// 输入流转换为输出流
ByteArrayOutputStream baos = cloneInputStream(inputStream);
// 打开新的输入流
InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
return stream1;
} catch (Exception e) {
log.error("文件下载异常:", e);
return null;
} finally {
if (channel != null) {
channel.disconnect();
}
}
}
}
Java实现服务器文件下载
8541

被折叠的 条评论
为什么被折叠?



