我正在尝试编写一个servlet,它将从远程位置读取(下载)文件并简单地将其作为响应发送,或者像代理一样执行,以隐藏实际文件的下载。我来自PHP背景,我可以像调用file_get_contents一样完成它。
使用servlet / jsp实现这一目标的任何方便方法?
由于
答案 0 :(得分:15)
这个怎么样? FileUtils (Commons IO 2.5-SNAPSHOT API)
示例 / src_directory_path /是远程服务器的安装目录。
@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());
}
答案 1 :(得分:3)
int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
File fileMp3 = new File("C:\Users\Ajay\*.mp3");
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "filename=\"hoge.txt\"");
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
downloadComplete = "-1";
excp.printStackTrace();
} finally {
os.close();
fis.close();
}