企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到要下载的文件名 String fileName = request.getParameter("filename"); // fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8"); // 找出这个文件 "/WEB-INF/upload"中的分隔符与平台无关,因为这是一个url地址 String path = this.getServletContext().getRealPath("/WEB-INF/upload") + File.separator + getPath(fileName); File file = new File(path + File.separator + fileName); // System.out.println(file.getName()); if (!file.exists()) { request.setAttribute("message", "对不起,您要下载的资源已被删除"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } // 得到文件的原始文件名 String oldName = file.getName().substring(file.getName().indexOf("_")+1); // 通知浏览器以下载的方式打开下面发送的数据 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(oldName, "UTF-8")); FileInputStream in = new FileInputStream(file); int len = 0; byte[] buffer = new byte[1024]; OutputStream out = response.getOutputStream(); while ((len=in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public String getPath(String fileName) { int hashCode = fileName.hashCode(); // 得到字符串在内存中的地址,如121221 int dir1 = hashCode & 15; // int dir1 = hashCode & 0xf; int dir2 = (hashCode >> 4) & 0xf; return dir1 + File.separator + dir2; // 得到诸如:3/5 } } ~~~