java静态资源文件_读取项目中静态资源文件下的所有文件,比如是所有图片

该博客介绍了一个Java后台辅助类FileBrowseUtil,用于读取指定文件夹路径下的所有静态资源,如图片。通过@RequestMapping("/getFileList")接口,接收前端传入的文件夹路径参数,返回一个包含所有文件绝对路径的ArrayList。实现中使用了递归遍历文件夹,获取目录和文件,并提供方法处理文件名和后缀。
摘要由CSDN通过智能技术生成

请求需要传入文件夹路径

这是后台代码

importjava.io.File;importjava.io.IOException;importjava.net.MalformedURLException;importjava.util.ArrayList;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;/*** 文件预览辅助类

*@authorzhy

**/@Controllerpublic classFileBrowseUtil {/*** 通过ajax请求获取传入的文件路径里边的文件fileList数组

*@paramreq

*@paramresp

*@paramparams 文件夹路径参数

*@return*@throwsServletException

*@throwsIOException

*@throwsMalformedURLException*/@RequestMapping("/getFileList")

@ResponseBodyprotected ArrayListCalculateGeoServlet(HttpServletRequest req,

HttpServletResponse resp,String params)throwsServletException, IOException,

MalformedURLException {

ArrayList fileList=new ArrayList();

String dir=req.getSession().getServletContext().getRealPath(params);

fileList=getFiles(dir);returnfileList;

}/*** 通过递归得到某一路径下所有的目录及其文件

*@paramfilePath 文件路径

*@return

*/

public ArrayListgetFiles(String filePath) {

ArrayList fileList = new ArrayList();

File root= newFile(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);

}*/

returnfileList;

}/*** 保留文件名及后缀*/

publicString getFileNameWithSuffix(String pathandname) {int start = pathandname.lastIndexOf("\\");if (start != -1) {return pathandname.substring(start + 1);

}else{return null;

}

}/*** 仅保留文件名不保留后缀*/

publicString 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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值