2

I am implementing a file download feature via a servlet and tried using Files.probeContentType without success, it doesn't seem to pick up the right MIME type, so I use a default of application/octet-stream when that happens. In my testing, that setting seems to work ok with all the various file types like tar, gif, gz, mp4, xml, json, work as in the files are downloaded correctly and can be opened with their respective apps.

First question, if anyone can tell me what I am doing wrong with probeContentType or a better way to determine the mime type, that'll be most appreciated, here are the few lines of code in Scala

val is = new FileInputStream(file)
val mt = Files.probeContentType(file.toPath)
val mimetype = if (mt == null) "application/octet-stream" else mt

Regardless, is it ok to always set the HTTP response content-type to application/octet-stream? I have only tested with Chrome and Firefox.

UPDATE In case anyone is wondering, I ended up using MimeUtil courtesy of this post. It works great so far for all the file types I have thrown at it. Here's the snippet of Scala code

import eu.medsea.mimeutil.MimeUtil
val file = new File("path-to-your-file")
MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector")
val mt = MimeUtil.getMimeTypes(file).toString

Here's a post with helpful code snippets for a few MIME type detection libraries.

Community
  • 1
  • 1
Bob
  • 8,424
  • 17
  • 72
  • 110

0 Answers0