0

I tried to use nio to download photo file by API, but I am not sure how to create a channel to response, is this code correct?

@RequestMapping(value = "/photosFast/{filename}.jpg", method = RequestMethod.GET)
@ResponseBody
...
FileChannel srcChannel = new FileInputStream(src.getAbsolutePath()).getChannel();
FileChannel destChannel = new FileOutputStream(response.getHeader("localtion")).getChannel();
try {
    srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
    srcChannel.close();
    destChannel.close();
}
...
mikezang
  • 2,291
  • 7
  • 32
  • 56
  • One, you can open a file channel "directly" by using `FileChannel.open`. Two, you should use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) to close your channels properly. And finally, you say you're tying to _download_ a file. That implies a remote source, but I only see you opening files. Where is your network access? – Slaw May 17 '19 at 03:23
  • This is an API on server, I want to put file to response. – mikezang May 17 '19 at 03:33
  • You seem to be using a framework (e.g. Spring, JavaEE, etc.). Are you sure you should be manually downloading the file? Or does the framework provide a way to say "here's the file, handle sending it for me"? – Slaw May 17 '19 at 15:03
  • I am using Spring MVC, do you have any idea? – mikezang May 17 '19 at 22:26
  • Maybe [Downloading a file from spring controllers](https://stackoverflow.com/questions/5673260/) and/or [`Files.copy`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/nio/file/Files.html#copy(java.nio.file.Path,java.io.OutputStream)) can help you. – Slaw May 17 '19 at 23:13
  • That is too slow, a 7m file will spend more than 70s to download! So I want to find a faster way... – mikezang May 18 '19 at 05:59
  • The speed performance of downloading a file will be dominated by the network, not by Java. – Slaw May 18 '19 at 06:04

0 Answers0