【发布时间】:2015-02-28 17:35:51
【问题描述】:
我想从 Spring 控制器返回一个文件。我已经有了可以给我任何 OutputStream 实现的 API,然后我需要将它发送给用户。
所以流程是这样的:
获取输出流->服务将此输出流传递给控制器->控制器必须将其发送给用户
我想我需要输入流来做这件事,我还发现了 Apache Commons api 功能,看起来像这样:
IOUtils.copy(InputStream is, OutputStream os)
但问题是,它将其转换到另一端 -> 不是从 os 到 is,而是从 is 到 操作系统。
编辑
要清楚,因为我看到答案不是正确的:
我使用 Dropbox api 并在 OutputStream 中接收文件,我希望在输入一些 URL 时将此输出流发送给用户
FileOutputStream outputStream = new FileOutputStream(); //can be any instance of OutputStream
DbxEntry.File downloadedFile = client.getFile("/fileName.mp3", null, outputStream);
这就是为什么我在谈论将 outputstream 转换为 inputstream,但不知道如何去做。此外,我认为有更好的方法来解决这个问题(可能以某种方式从输出流返回字节数组)
我试图通过参数将 servlet 输出流 [response.getOutputstream()] 传递给从保管箱下载文件的方法,但它根本不起作用
编辑 2
我的应用程序的“流程”是这样的:@Joeblade
用户输入网址:/download/{file_name}
-
Spring Controller 捕获 url 并调用 @Service 层下载文件并将其传递给该控制器:
@RequestMapping(value = "download/{name}", method = RequestMethod.GET) public void getFileByName(@PathVariable("name") final String name, HttpServletResponse response) throws IOException { response.setContentType("audio/mpeg3"); response.setHeader("Content-Disposition", "attachment; filename=" + name); service.callSomeMethodAndRecieveDownloadedFileInSomeForm(name); // <- and this file(InputStream/OutputStream/byte[] array/File object/MultipartFile I dont really know..) has to be sent to the user } -
现在@Service 调用Dropbox API 并通过指定的file_name 下载文件,并将其全部放入OutputStream,然后传递它(以某种形式..可能是 OutputStream、byte[] 数组或任何其他对象——我不知道哪个更好用)到控制器:
public SomeObjectThatContainsFileForExamplePipedInputStream callSomeMethodAndRecieveDownloadedFileInSomeForm(final String name) throws IOException { //here any instance of OutputStream - it needs to be passed to client.getFile lower (for now it is PipedOutputStream) PipedInputStream inputStream = new PipedInputStream(); // for now PipedOutputStream outputStream = new PipedOutputStream(inputStream); //some dropbox client object DbxClient client = new DbxClient(); try { //important part - Dropbox API downloads the file from Dropbox servers to the outputstream object passed as the third parameter client.getFile("/" + name, null, outputStream); } catch (DbxException e){ e.printStackTrace(); } finally { outputStream.close(); } return inputStream; } 控制器接收文件(我根本不知道我上面所说的格式)然后传递给用户
所以事情是通过调用dropboxClient.getFile()方法接收带有下载文件的OutputStream,然后这个包含下载文件的OutputStream必须发送给用户,怎么做?
【问题讨论】:
标签: java spring file spring-mvc