1

我想下载服务器本身可用的文件

AppName\resources\attachemnts\file.extension(this can be anything)我从网上得到了代码,以下是相同的。

@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());
            }
        }

我必须设置res.setContentType("application/xls");动态,因为文件类型每次都会不同。

如何获取文件类型?

4

1 回答 1

1

为了确定文件的类型,您可以使用任何检查文件的魔法数字并返回其文件类型的库。例如:

另请参阅相关问题:

于 2013-01-09T14:02:57.277 回答