我想下载服务器本身可用的文件
AppName\resources\attachemnts\file.extension(这可以是任何内容)
我从网上得到了代码,以下是相同的。
@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");
设置为动态,因为文件类型每次都会不同。
如何获取文件类型?
最佳答案
为了确定文件类型,您可以使用任何检查 file's magick numbers 的库并返回其文件类型。例如:
另请参阅相关问题:
关于java - 下载文件时如何在 Spring 中动态设置 res.setContentType ("application/xls"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232233/