如何在服务器响应上写入文件对象而不在服务器上保存文件?
我正在将 Spring 与 DWR 一起使用。我想返回一个文件对象作为响应,但是我将文件(要发送)保存在服务器临时位置,然后将其位置作为锚标记的 href 发送到客户端,但是我想知道是否有办法抛出将文件直接发送到响应对象上的浏览器,而不将其临时保存在服务器上。
我期望是否有一种方法可以通过 DWR 发送文件作为响应。
I am using Spring with DWR . I want to return a file object as response , however I save the file (to be sent) at server temporary location and then send its location as href for anchor tag on client side , however I wonder if there could be a way to throw the file directly to browser on response object without saving it temporarily on server.
I expected if there could be a way to send file as a response via DWR.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我使用 Spring 已经很多年了,而且我对 DWR 也不熟悉,但你问题的本质是网络的基础。
答案是肯定的,可以。实际上,您需要设置 HTTP 标头 Content-Disposition: Attachment,然后流式传输内容。所有这些都将在对原始请求的响应中(而不是发回链接)。
实现此目的的实际代码将取决于您的情况,但这应该可以帮助您入门。
It has been years since I've used Spring, and I'm unfamiliar with DWR, but the essence of your question is basic to the web.
The answer is yes, you can. In effect, you need to set the HTTP header Content-Disposition: attachment, then stream down the contents. All of this will be in the response to the original request (as opposed to sending back a link).
The actual code to achieve this will depend on your circumstances, but this should get you started.
你从 Java 脚本调用该方法,对吗?我不太明白 Spring 在这个流程中是如何相关的,但据我所知,DWR 允许您生成 Java 脚本存根并直接从您的 java 脚本客户端代码在服务器上调用公开 bean 的 Java 方法。
您可以逐字节读取文件并从 java 方法返回它,只要它确实返回字节数组即可。
但是,您会在客户端上处理这个字节数组吗?
我只是认为在这个特定的流程中你不应该使用 DWR,而应该发出一个普通的 AJAX 请求(如果 DWR 可以以某种方式包装它以方便 - 太好了)。这个请求不应该到达 DWRServlet,而应该由常规 servlet/一些基于 Web 的框架(例如 Spring MVC)来处理:)
一旦请求到达 servlet,请使用
response.setHeader("Content-Disposition","attachment; filename=test.txt");
正如已经指出的。
希望这有帮助,
祝你好运!
标记
you call the method from Java Script, right? I didn't really understand how Spring is related in this flow, but as far as I know DWR allows you to produce Java Script Stubs and call the Java methods of the exposed bean directly on server right from your java script client code.
You can read the file byte-by-byte and return it from your java method as long as it really returns a byte array.
However what would you do with this byte array on client?
I just think in this specific flow you shouldn't use the DWR but rather issue an ordinar AJAX request (if DWR can wrap it somehow for convenience - great). This request shouldn't come to DWRServlet, but rather be proceeded by a regular servlet/some web-based framework, like Spring MVC :)
Once the request comes to the servlet, use
response.setHeader("Content-Disposition","attachment; filename=test.txt");
as was already stated.
Hope this helps,
Good luck!
Mark
返回 Excel 以从客户端下载的示例:
//Java 端:
//Javascript 端:
An example which return a excel to download from client:
//Java side:
//Javascript side: