Java Questions
Java Questions

Reputation: 7963

how to set res.setContentType("application/xls") dynamic in spring while downloading the file

I want to download a file which is available in the server itself

AppName\resources\attachemnts\file.extension(this can be anything) i have got the code from the net the following is the same.

@RequestMapping(value = "/fileDownload", method = RequestMethod.GET)
        public void handleFileDownload(@RequestParam("fileLocation") String fileLocation,HttpServletResponse res) {
            try {

                URL url = getClass().getResource(fileLocation);
                File f = new File(url.toURI());
                System.out.println("Loading file "+fileLocation+"("+f.getAbsolutePath()+")");
                if (f.exists()) {
                    res.setContentType("application/xls");
                    res.setContentLength(new Long(f.length()).intValue());
                    res.setHeader("Content-Disposition", "attachment; filename=Test.xls");
                    FileCopyUtils.copy(new FileInputStream(f), res.getOutputStream());
                } else {
                    System.out.println("File"+fileLocation+"("+f.getAbsolutePath()+") does not exist");
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

i have to set res.setContentType("application/xls"); dynamic since the file type is going to be different each time.

How to get file type?

Upvotes: 1

Views: 3246

Answers (1)

Slava Semushin
Slava Semushin

Reputation: 15214

For determining type of file, you may use any library which checks file's magick numbers and returns its filetype. For example:

See also related questions:

Upvotes: 1

Related Questions