讀取專案中靜態資原始檔下的所有檔案,比如是所有圖片,,補充:注意一下windows與linux對於檔案的路徑顯示不同(反斜槓與正斜槓)

小哥哥呀發表於2018-10-09
請求需要傳入資料夾路徑

這是後臺程式碼
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; } } }

 

相關文章