1

I have saved all types of file without extension. When reading through Java code, how to get content type of file?

File file = "/admin/sun"
byte[] pdfByteArray = FileUtils.readFileToByteArray(file);
if (fileName.endsWith(".pdf")) {
    response.setContentType("application/pdf");
} else {
    response.setContentType("image/jpeg");
}
response.getOutputStream().write(pdfByteArray);
response.getOutputStream().flush();

What is if the file extension .pdf or .jpeg it is working then without extension how to get content-type?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Maheshbabu Jammula
  • 357
  • 1
  • 2
  • 11

2 Answers2

2

Use Files.probeContentType(path) in jdk7. Or detect the file type yourself, according to different file type specifications. Say pdf http://www.adobe.com/devnet/pdf/pdf_reference.html

Weibo Li
  • 3,565
  • 3
  • 24
  • 36
  • I test that with some csv files (with extension), and method returns text/csv, but if I delete the extension from file's name, it doesn't work. It returns text/plain – Angie Quijano Jun 12 '19 at 16:05
1

You better do not rely on extensions. Find the mime type of the file.

See this SO question: Getting A File's Mime Type In Java

You must read the mime type with Files.probeContentType(path).

More relevant information on mime types

Community
  • 1
  • 1
ssedano
  • 8,322
  • 9
  • 60
  • 98