0

I have implemented sparkjava framework on Android for embedded web server to serve files from android device, and it is able to list files on web page, but the issue is when downloading file from android device using web interface unable to download files with file size greater than 70-80 MB.

Android app(sender, host, server) running embedded http webserver using sparkjava and receiving side is desktop web browser connected to mobile hotspot which is running android app.

If file size is more than 70-80 MB Android Studio log show 'Out of Memory'

Image of webpage listing files from android device and here Android studio log

Using below kotlin code to provide downloadable file to web browser(the downloadable file is from android device)

httpService.get("/download/:file") { req, res ->
  val fileParam = decode(req.params(":file"))
  val filePath = Paths.get(fileParam)
  val bytes: ByteArray = Files.readAllBytes(filePath)
  val raw: HttpServletResponse = res.raw()

  raw.outputStream.write(bytes)
  raw.outputStream.flush()
  raw.outputStream.close()

  res.raw
}

The above code is in Android app.

How to solve this issue?

  • Do not put all the bytes of the file in a byte array first. Wrong approach as it leads to memory problems as you have seen. Just take a buffer of say 8192 bytes and in a loop read from inputstream in that buffer and then directly write them to outputstream. – blackapps Oct 23 '20 at 09:37
  • Problem occurred at sending side (android) – speedy.user Oct 23 '20 at 10:13
  • Trying to build file server app in android for that I am embedding sparkjava web framework, only issue is downloading large file as shown in attached image. – speedy.user Oct 23 '20 at 10:15
  • @blackapps can you provide a code snippet for your suggestion? – speedy.user Oct 23 '20 at 10:18
  • No, the posted code is not mine, using that code for testing, it is from https://stackoverflow.com/a/27944837/11364354 – speedy.user Oct 23 '20 at 10:57
  • The setup is Android app(sender, host, server) running embedded http webserver using sparkjava and receiving side is desktop web browser connected to mobile hotspot which is running android app. – speedy.user Oct 23 '20 at 11:03
  • You are correct it is sending to web browser. – speedy.user Oct 23 '20 at 11:06
  • Think if you tell @thouliha about his answer and your problem things will be solved soon. Why didnt you there? – blackapps Oct 23 '20 at 11:46
  • Its working fine now, as you said "Do not put all the bytes of the file in a byte array first, Just take a buffer", But I have a question what should be buffer size? currently using 8192 bytes. – speedy.user Oct 23 '20 at 15:38
  • 8192 is ok. -As i said so ;-)- But you could experiment and test a bit to find a better size. Use powers of two. – blackapps Oct 23 '20 at 16:20
  • Okay, Thanks. Will experiment more. – speedy.user Oct 23 '20 at 19:09

0 Answers0