写了一个简单的代码从文件系统下载文件,但仍然没有下载弹出,因此文件没有下载,甚至没有抛出任何错误。请帮助我。以下是我的代码写在控制器端。
@RequestMapping(value = "download", method=RequestMethod.POST)
public @ResponseBody void download(HttpServletRequest request, HttpServletResponse response){
String fileName="/home/test/Testing.xlsx";
PrintWriter out=null;
try{
System.out.println(fileName.substring(fileName.lastIndexOf('/')+1)+"fileName");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader( "Pragma", "public" );
response.setHeader("Content-Disposition", "attachment; filename=" + fileName.substring(fileName.lastIndexOf('/')+1) );
out = response.getWriter();
int i;
FileInputStream inputStream = new FileInputStream(fileName);
while ((i = inputStream.read()) != -1) {
out.write(i);
}
inputStream.close();
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
答案 0 :(得分:0)
这里的错误是POST方法,我们不应该使用post方法而应该在编写下载程序时始终使用GET方法。
@RequestMapping(value = "download", method=RequestMethod.GET)
public @ResponseBody void download(HttpServletRequest request, HttpServletResponse response){
String fileName="/home/test/Testing.xlsx";
PrintWriter out=null;
try{
System.out.println(fileName.substring(fileName.lastIndexOf('/')+1)+"fileName");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader( "Pragma", "public" );
response.setHeader("Content-Disposition", "attachment; filename=" + fileName.substring(fileName.lastIndexOf('/')+1) );
out = response.getWriter();
int i;
FileInputStream inputStream = new FileInputStream(fileName);
while ((i = inputStream.read()) != -1) {
out.write(i);
}
inputStream.close();
out.close();
}
catch(Exception e){
System.out.println(e);
}
}