Java返回文件流数据,转压缩包返回文件流

最近项目中有一个下载文件的功能,然后前端让后端接口返回文件流数据:

1、直接返回文件流:

首先使用FileInputStream读取文件内容,然后设置HTTP响应头信息,包括文件类型和下载时的文件名。最后使用IOUtils.copy()将文件内容写入到HTTP响应流中,实现返回文件流的功能。

public void download(String fileName, HttpServletResponse resp) {
    String path = new File("").getAbsolutePath();
    String filePath = path + "/" + fileName;

    File file = new File(filePath);
    try (FileInputStream fis = new FileInputStream(filePath)){
        resp.setHeader("Content-Type", "application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment;filename=" +file.getName());
        IOUtil.copy(fis, resp.getOutputStream());
        resp.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
代码解析
FileInputStream

FileInputStream是Java IO流中用于读取文件的一个类。它继承自InputStream,可以读取一个文件的字节流,并将其传递给Java程序。在本示例中,我们使用FileInputStream读取文件的字节流。

HttpServletResponse

HttpServletResponse是Java Web应用中用于响应HTTP请求的一个类。它继承自ServletResponse,包含了响应HTTP请求的常用方法,比如设置响应头信息、获取输出流等。在本示例中,我们使用HttpServletResponse将文件内容写入到HTTP响应流中。

IOUtils

IOUtils是Apache Commons IO中提供的一个类,用于在Java IO操作中提供更方便的常用方法。在本示例中,我们使用IOUtils.copy()FileInputStream中的文件内容复制到HttpServletResponse的输出流中,实现返回文件流的功能。

try-with-resources

try-with-resources 语句来确保资源(比如流或者连接)在使用完毕后被正确关闭。try-with-resources 语句可以自动关闭资源,而不需要显式使用 finally 块来进行关闭操作。

2、转成压缩包再返回文件流:

当下载文件比较大时,下载会很耗时,此时可以先把文件转成压缩包保存到本地,然后再转成文件流返回;

public void download(String fileName, HttpServletResponse resp) {
    String path = new File("").getAbsolutePath();
    String filePath = path + "/" + fileName;
    String zipFilePath = path + "/" + fileName + ".zip";
    // 转成压缩包
    this.convertFileToZip(filePath, zipFilePath);
    File file = new File(zipFilePath);
    try (FileInputStream fis = new FileInputStream(zipFilePath)){
        resp.setHeader("Content-Type", "application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment;filename=" +file.getName());
        IOUtil.copy(fis, resp.getOutputStream());
        resp.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void convertFileToZip(String filePath, String zipFilePath) {
    File file = new File(filePath);
    try (FileOutputStream fos = new FileOutputStream(filePath);
         ZipOutputStream zos = new ZipOutputStream(fos);
         FileInputStream fis = new FileInputStream(file)) {
        zos.putNextEntry(new ZipEntry(file.getName()));
        byte[] buffer = new byte[1024];
        int byteRead;

        while ((byteRead = fis.read(buffer)) != -1) {
            zos.write(buffer, 0 , byteRead);
        }
        zos.closeEntry();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要发送一个 Java POST 请求并返回一个 Zip 压缩包文件,你可以使用 JavaHttpURLConnection 类。以下是一个示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class ZipRequestExample { public static void main(String[] args) throws Exception { // 创建 URL 对象和 HttpURLConnection 对象 URL url = new URL("http://example.com/api/download"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法和请求头 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); // 构造请求体 String requestBody = "filename=myfile.zip"; // 发送请求 OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); outputStream.close(); // 检查响应状态码 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // 获取响应并解压缩 InputStream inputStream = connection.getInputStream(); ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 处理 ZipEntry 数据 } zipInputStream.close(); inputStream.close(); } else { // 处理错误 } // 断开连接 connection.disconnect(); } } ``` 这个示例代码中,我们首先创建了一个 URL 对象和 HttpURLConnection 对象,并设置了请求方法和请求头。然后,我们构造了一个请求体,将其写入请求中。最后,我们检查响应状态码,如果响应状态码为 HTTP_OK,就获取响应并使用 ZipInputStream 解压缩。你可以在 while 循环中处理每个 ZipEntry 的数据,例如将其写入文件或内存中。最后,我们断开连接以释放资源。注意,这个示例代码中的 URL、请求方法、请求头和请求体都需要根据你的实际情况进行修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值