c++ 获取文件的hashcode_jsp 实现文件上传和下载
????????文件上傳。
????????需要注意。
????????form 表單要設置屬性 enctype="multipart/form-data"。
????????文件名要用 UUID.randomUUID() 重組,否則相同文件名會覆蓋。UUID.randomUUID() 每次取值不同且唯一。
????????文件過多不容易管理,需要用未 UUID.randomUUID() 重組的文件名取 hashcode 值計算后分散文件夾。
????????為了安全性,文件最好放在 WEB-INF 文件夾。并且路徑是編譯后的 out 文件夾。路徑采用 this.getServletContext().getRealPath("WEB-INF") + File.separator + "png" 獲得。
????????Servlet 一定要加注解 @MultipartConfig
????????文件類型,可以在 Tomcat/conf/web.xml 查找對應。
????????部分代碼。
// jsp部分<form method="post" action="uploadServlet/upload" enctype="multipart/form-data"> username:<input type="text" name="username" value="張三"><br> age:<input type="text" name="age" value="13"><br> file1:<input type="file" name="file1"><br> file2:<input type="file" name="file2"><br> file3:<input type="file" name="file3"><br> <input type="submit" value="提交"> form>@WebServlet("/UploadServlet/*")@MultipartConfig(maxFileSize = 1024 * 1024 * 10)public class UploadServlet extends DispatcherServlet { private List<String> typeList = Arrays.asList("image/jpeg","image/png"); public void upload(HttpServletRequest request, HttpServletResponse response) { try { Collection parts = request.getParts(); for (Part part: parts) { System.out.println("content: " + part.getContentType()); System.out.println("name: " + part.getName()); System.out.println("filename: " + part.getSubmittedFileName()); Collection<String> headerNames = part.getHeaderNames(); for (String str: headerNames) { System.out.println("headers: "); System.out.println(str + "\t" + part.getHeader(str)); } String fileName = part.getSubmittedFileName(); if (fileName != null && fileName.length() > 0) { // 是文件 if (!typeList.contains(part.getContentType())) { response.getWriter().write("不支持的類型--" + part.getSubmittedFileName()); continue; } String totalName = dirPath(fileName) + File.separator + fileName(fileName); System.out.println("totalName: " + totalName); // 將文件寫入當前路徑 part.write(totalName); } else { // 普通文本表單 String username = request.getParameter("username"); String age = request.getParameter("age"); System.out.println("username:" + username + "\t" + age); } System.out.println("========= ========="); } } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } // 組文件名 public String fileName(String fileName) { String s = UUID.randomUUID().toString().replace("-", ""); return s.concat("-").concat(fileName); } // 分散文件夾名 public String dirPath(String fileName) { int hashCode = fileName.hashCode(); // 一級目錄 int dir1 = Math.abs(hashCode % 10); // 二級目錄 int dir2 = Math.abs((hashCode >> 4) % 10); // 工程目錄, 在 out 里 String realPath = this.getServletContext().getRealPath("/"); String filePath = realPath + File.separator + "WEB-INF" + File.separator + "png" + File.separator + dir1 + File.separator + dir2; File file = new File(filePath); if (!file.exists()) { boolean mkdirs = file.mkdirs(); if (!mkdirs) { System.out.println("創建文件夾失敗"); } } return filePath; }}????????文件下載。??
????????需要注意。
????????從文件夾中遞歸出所有文件。
????????為了安全,不直接存儲文件路徑,而是存儲文件原名,重新計算出文件路徑。????
????????解決文件名下載后亂碼問題。使用 URLEncoder 編碼文件名,瀏覽器會自動解碼。
????????要設置 header 屬性 content-disposition 才能下載文件到本地。
????????部分代碼。
// jsp 部分<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html><head> <title>Titletitle>head><body> <table border="1"> <tr> <th>圖片名th> <th>圖片th> <th>下載th> tr> <c:forEach items="${fileMap}" var="map"> <tr> <td>${map.key}td> <td> <img style="width: 200px;" src="DownloadServlet/getFileStream?fileName=${map.value}"> td> <td> <a href="DownloadServlet/getFileStream?fileName=${map.value}&type=download">下載a> td> tr> c:forEach> table>body>html>@WebServlet("/DownloadServlet/*")public class DownloadServlet extends DispatcherServlet { // 獲取所有文件 public String getFileName(HttpServletRequest request, HttpServletResponse response) { Map<String, String> map = new HashMap<>(); String filePath = this.getServletContext().getRealPath("WEB-INF") + File.separator + "png"; File file = new File(filePath); getFileNameMap(file, map); // 存儲在域中,頁面通過 jstl 取出 request.setAttribute("fileMap", map); return ConstUtils.FORWARD + ":download.jsp"; } // 從文件夾中 遞歸出所有文件名 并存儲在 map 中 public void getFileNameMap(File file, Map<String, String> map) { if (file.exists()) { File[] files = file.listFiles(); for (File sfile : files) { if (sfile.isDirectory()) { getFileNameMap(sfile, map); } else { String fileName = sfile.getName(); String path = sfile.getPath(); System.out.println("fileName:" + fileName + "\t" + "path:" + path); String realName = fileName.substring(fileName.indexOf("-") + 1); map.put(realName, fileName); } } } } // 獲取顯示文件的流 public void getFileStream(String fileName, String type,HttpServletResponse response) { String realName = fileName.substring(fileName.indexOf("-") + 1); String filePath = dirPath(realName) + File.separator + fileName; FileInputStream ips = null; try { ips = new FileInputStream(filePath); // 下載 if (type.equals("download")) { // 處理文件名亂碼問題 String encode = URLEncoder.encode(realName, "utf-8"); // 設置響應頭 response.setHeader("content-disposition", "attachment;filename="+encode); } byte[] bytes = new byte[1024]; int read = -1; while ((read = ips.read(bytes, 0 ,bytes.length)) != -1) { // 輸出到頁面接收顯示 或 下載 response.getOutputStream().write(bytes, 0 ,read); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ips != null) { try { ips.close(); } catch (IOException e) { e.printStackTrace(); } } } } // 分散文件夾名 public String dirPath(String fileName) { int hashCode = fileName.hashCode(); // 一級目錄 int dir1 = Math.abs(hashCode % 10); // 二級目錄 int dir2 = Math.abs((hashCode >> 4) % 10); // 工程目錄, 在 out 里 String realPath = this.getServletContext().getRealPath("WEB-INF"); String filePath = realPath + File.separator + "png" + File.separator + dir1 + File.separator + dir2; return filePath; }}總結
以上是生活随笔為你收集整理的c++ 获取文件的hashcode_jsp 实现文件上传和下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rediscluster全局数据_red
- 下一篇: mysql在线模拟器_SQL在线模拟器