9

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

2 Answers 2

18

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

req and res parameters of doGet method must be request and response
Hi. AndroidCodeHunter. Thank you for your suggest.
If you would like user to be asked to save file rather than to display its content by browser add attachment parameter: resp.setHeader("Content-Disposition", "attachment; filename=\"hoge.txt\"")
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();
}

2 Comments

Thanks for your answer. I'm trying to send a binary (mp3) file... will that work this way?
Thanks. Will test and let you know. BTW does it work for remote files?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.