zoukankan      html  css  js  c++  java
  • 读取项目中静态资源文件下的所有文件,比如是所有图片,,补充:注意一下windows与linux对于文件的路径显示不同(反斜杠与正斜杠)

    请求需要传入文件夹路径

    这是后台代码
    import
    java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 文件预览辅助类 * @author zhy * */ @Controller public class FileBrowseUtil { /** * 通过ajax请求获取传入的文件路径里边的文件fileList数组 * @param req * @param resp * @param params 文件夹路径参数 * @return * @throws ServletException * @throws IOException * @throws MalformedURLException */ @RequestMapping("/getFileList") @ResponseBody protected ArrayList<String> CalculateGeoServlet(HttpServletRequest req, HttpServletResponse resp,String params) throws ServletException, IOException, MalformedURLException { ArrayList<String> fileList=new ArrayList<String>(); String dir = req.getSession().getServletContext().getRealPath(params); fileList=getFiles(dir); return fileList; } /** * 通过递归得到某一路径下所有的目录及其文件 * @param filePath 文件路径 * @return */ public ArrayList<String> getFiles(String filePath) { ArrayList<String> fileList = new ArrayList<String>(); File root = new File(filePath); File[] files = root.listFiles(); for (File file : files) { if (file.isDirectory()) { /* * 递归调用 */ getFiles(file.getAbsolutePath()); fileList.add(file.getAbsolutePath()); } else { String picPathStr = file.getAbsolutePath(); // String picPathStr = file.getAbsolutePath().replaceAll("\\","//"); fileList.add(getFileNameWithSuffix(picPathStr)); } } /*for(String str:fileList){ System.out.println(str); }*/ return fileList; } /** * 保留文件名及后缀 */ public String getFileNameWithSuffix(String pathandname) { int start = pathandname.lastIndexOf("\"); if (start != -1 ) { return pathandname.substring(start + 1); } else { return null; } } /** * 仅保留文件名不保留后缀 */ public String getFileName(String pathandname) { int start = pathandname.lastIndexOf("\"); int end = pathandname.lastIndexOf("."); if (start != -1 && end != -1) { return pathandname.substring(start + 1, end); } else { return null; } } }
    如有疑问,欢迎留言讨论。
  • 相关阅读:
    对于在git上面拉代码报"error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054"解决方法
    在vue项目中如何添加eslint
    vscode编辑如何保存时自动校准eslint规范
    css3动画
    JS中的深拷贝与浅拷贝
    JS中的防抖与节流
    金三银四求职季,前端面试题小梳理(HTML、CSS、JS)
    正则表达式元字符大整理
    常规正则表达式练习,一起来开心的掉发吧
    关于子元素的margin-top对父级容器无效
  • 原文地址:https://www.cnblogs.com/zhhy/p/9762616.html
Copyright © 2011-2022 走看看