我在看公司的一个老网站系统源码。是SSM+JSP的。它打开一个网页后,都跳转到一段代码去下载图片。
难道不是直接在网页中写img标签的src属性就行了吗?只是里面有数据库读出的数,网页上写作变量名了。还总是跳到这段代码下。
有必要吗?
还是以前老技术的遗留?我记得我写Jsp也没有专门弄段代码处理图片啊。是更安全还是咋的。
public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filepath = req.getRequestURI();
int index = filepath.indexOf(Global.USERFILES_BASE_URL);
if(index >= 0) {
filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
}
try {
filepath = UriUtils.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e1) {
logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
}
File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
try {
FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
resp.setHeader("Content-Type", "application/octet-stream");
return;
} catch (FileNotFoundException e) {
req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
}
}
其中Global.USERFILES_BASE_URL是默认的文件目录。