欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

为忙碌的人们编写 - 用 Java 从 MinIO 服务器下载文件 (3)

最编程 2024-07-17 13:38:29
...
/** * 获取文件 * * @param bucketName bucket名称 * @param objectName 文件名称 * @return 二进制流 */ @SneakyThrows public InputStream getObject(String bucketName, String objectName) { return client.getObject(bucketName, objectName); } /** * 下载文件 * * @param fileUrl 文件绝对路径 * @param response * @throws IOException */ @GetMapping("downloadFile") public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException { if (StringUtils.isBlank(fileUrl)) { response.setHeader("Content-type", "text/html;charset=UTF-8"); String data = "文件下载失败"; OutputStream ps = response.getOutputStream(); ps.write(data.getBytes("UTF-8")); return; } try { // 拿到文件路径 String url = fileUrl.split("9000/")[1]; // 获取文件对象 InputStream object = minioUtils.getObject(MinioConst.MINIO_BUCKET, url.substring(url.indexOf("/") + 1)); byte buf[] = new byte[1024]; int length = 0; response.reset(); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(url.substring(url.lastIndexOf("/") + 1), "UTF-8")); response.setContentType("application/octet-stream"); response.setCharacterEncoding("UTF-8"); OutputStream outputStream = response.getOutputStream(); // 输出文件 while ((length = object.read(buf)) > 0) { outputStream.write(buf, 0, length); } // 关闭输出流 outputStream.close(); } catch (Exception ex) { response.setHeader("Content-type", "text/html;charset=UTF-8"); String data = "文件下载失败"; OutputStream ps = response.getOutputStream(); ps.write(data.getBytes("UTF-8")); } }

推荐阅读