动态文件下载,无需在服务器中保存文件 [英] Dynamic file download without saving file in the server

查看:29
本文介绍了动态文件下载,无需在服务器中保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apache POI 库对多个 excel 文件进行一些操作.

I am using Apache POI libraries to do some operation on multiple excel files.

我正在尝试下载 excel 报告而不将其存储在服务器中的某个位置.

I'm trying to download the excel report without storing it somewhere in the server.

我正在使用 Struts 2,它需要将文件输入 InputStream 而 POI Workbook 需要一个 OutputStream 来写入数据.

I am using Struts 2 which needs the file fed into a InputStream while POI Workbook needs a OutputStream to write the data into.

任何帮助都会很棒

推荐答案

既然你已经知道你需要一个 Stream 结果:

Since you already know you need a Stream result:

我正在使用 Struts 2,它需要将文件送入 InputStream

I am using Struts 2 which needs the file fed into a InputStream

// With Getter
private InputStream inputStream;

并且您已经知道如何使用 POI 创建 Excel:

and you already know how to create an Excel with POI:

POI Workbook 需要一个 OutputStream 来写入数据.

POI Workbook needs a OutputStream to write the data into.

public String execute(){

    // stuff 

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // fill the OutputStream with the Excel content
    workbook.write(baos);

那么唯一缺少的部分就是如何将 POI 的 OutputStream 转换为 Struts2 Stream 结果的 InputStream.这比其他的更容易..:

then the only missing piece is how to convert the POI's OutputStream into the Struts2 Stream result's InputStream. And this is easier than the rest..:

    // Create an Input Stream from the bytes extracted by the OutputStream
    inputStream = new ByteArrayInputStream(baos.toByteArray());

    return SUCCESS;
}

这篇关于动态文件下载,无需在服务器中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆