Java servlet read a file and send it as response

谁说胖子不能爱 提交于 2019-12-17 19:05:29

问题


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.

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

Thanks


回答1:


How about this one? FileUtils (Commons IO 2.5-SNAPSHOT API)

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());
}

Was this by any chance what you wanted to hear?

@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());
}



回答2:


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();
}


来源:https://stackoverflow.com/questions/20342457/java-servlet-read-a-file-and-send-it-as-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!