新手在这里,在下面它将文件作为参数并将其连接到目录字符串,然后查找文件并使用流获取文件并将其提供给浏览器以供下载。此代码容易受到目录遍历的影响,我不确定如何加强代码以抵消这种情况。
<%
if(request.getParameter("file")!=null)
{
String context = request.getContextPath();
int BUFSIZE = 4096;
String filePath;
filePath = request.getParameter("file");
File file = new File(getServletContext().getRealPath("/") +context);
file = new File(file.getParent()+"/documents/"+filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
//response.setContentType("text/html");
response.setContentLength((int)file.length());
String fileName = (new File(filePath)).getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//response.setHeader("Content-Disposition", "attachment; filename=\"" +new Random().nextInt(10000)+ "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
else
{
}
%>