页面发送请求至后台,后台传输文件至前台代码:
byte[] tempContent = null;
fileStream = new FileInputStream(filePath);
tempContent = new byte[fileStream.available()];
fileStream.read(tempContent, 0, fileStream.available());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
response.getOutputStream().write(tempContent);
修改MIME Type以获取不同的文件,如图片、excel等response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
注意事项:
1、页面不要传递路径到后台,因为在linux服务器中传递路径中的"/"到后台时会被转义,以至于获取不到文件,最好是将路径保存到数据库中,传递ID到后台再查询文件路径;
2、数据库中路径的字段类型需定义为vchar、character varing等可变类型,因为取路径时,定长字段会自动补充空格,如路径长度为50,字段长度为100,所取路径会自动补充50个空格至100,在windows服务器下可正常下载,但在linux服务器下则找不到文件路径。