Java servlet读取文件并将其作为响应发送 [英] Java servlet read a file and send it as response

查看:458
本文介绍了Java servlet读取文件并将其作为响应发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个servlet,它将从远程位置读取(下载)文件并简单地将其作为响应发送,或者像代理一样,以隐藏实际文件的下载。我来自PHP背景,我可以像调用 file_get_contents 一样。

I'm trying to write a servlet which will read (download) file from a remote location and simply send it as response, acting more-or-less like a proxy to hide the actual file from getting downloaded. I'm from a PHP background where I can do it as simply as calling file_get_contents.

使用servlet / jsp实现这一目标的任何方便方法?

Any handy way to achieve this goal using servlet/jsp?

谢谢

推荐答案

这个怎么样?
FileUtils(Commons IO 2.5-SNAPSHOT API)

示例
/ src_directory_path /是远程服务器的安装目录。

example /src_directory_path/ is mount directory of remote server.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    resp.setContentType("application/octet-stream");
    resp.setHeader("Content-Disposition", "filename=\"hoge.txt\"");
    File srcFile = new File("/src_directory_path/hoge.txt");
    FileUtils.copyFile(srcFile, resp.getOutputStream());
}

您有什么想听到的吗?

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  InputStream in = new URL( "http://remote.file.url" ).openStream();
  IOUtils.copy(in, response.getOutputStream());
}

这篇关于Java servlet读取文件并将其作为响应发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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