Java实现读取指定服务器文件并通过浏览器下载

Java实现服务器文件下载

一、前端部分

前端下载按钮:

<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();
			}
		}
	}



}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值