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

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

问题描述

我正在尝试编写一个 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天全站免登陆