【JAVA企业级开发】Springboot通过url请求遍历访问服务器项目外部静态资源拒绝或者404?教你使用Java+Js实现运行在服务器的项目中遍历项目外部资源文件夹下所有文件并显示在客户端页面上

    技术2024-11-12  8

    第一步:获取本地文件夹中的所有图片路径

    springboot默认可以访问resources下的static文件夹下的静态资源,我们一般将图片指定上传到static下的某个文件夹,例如images,开发阶段可以使用,但是当项目打成jar包就无法使用,运行会报出无法找到文件路径。这时候就需要配置虚拟路径,用来指定到硬盘下的固定地址。

    1 SpringBoot配置虚拟化路径用于图片的展示

    package baobaobaobao.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Created by @author LiuChunhang on 2020/6/16. */ @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //就是说 url 中出现 resourceHandler 匹配时,则映射到 location 中去,location 相当于虚拟路径 //映射本地文件时,开头必须是 file:/// 开头,表示协议 //registry.addResourceHandler( "picture/**").addResourceLocations("/root/picture/"); System.out.println("静态请求通过虚拟路径到外部资源映射"); registry.addResourceHandler( "/view/**").addResourceLocations("file://"); } }

    2dao层

    package baobaobaobao.dao; import baobaobaobao.entity.FilePath; import java.util.List; /** * Created by @author LiuChunhang on 2020/6/23. */ public interface FilePathMapper { //记录文件信息 int picture(FilePath filePath); //验证查库 List<String > path(); }

    3service层

    package baobaobaobao.service; import baobaobaobao.entity.FilePath; import java.util.List; /** * Created by @author LiuChunhang on 2020/6/23. */ public interface FilePathServiceFace { /**记录文件信息*/ int picture(FilePath filePath); List<String> path(); } package baobaobaobao.service; import baobaobaobao.dao.FilePathMapper; import baobaobaobao.entity.FilePath; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by @author LiuChunhang on 2020/6/23. */ @Service public class FilePathService implements FilePathServiceFace { @Autowired public FilePathMapper filePathMapper; public FilePathMapper getFilePathMapper() { return filePathMapper; } public void setFilePathMapper(FilePathMapper filePathMapper) { this.filePathMapper = filePathMapper; } @Override public int picture(FilePath filePath) { int picture = filePathMapper.picture(filePath); return picture; } @Override public List<String> path() { List<String> path = filePathMapper.path(); return path; } }

    4 controller层

    package baobaobaobao.controller; import baobaobaobao.service.FilePathServiceFace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.List; /** * Created by @author LiuChunhang on 2020/6/23. */ @Controller public class ManyFileloadController { @Autowired public FilePathServiceFace filePathService; public FilePathServiceFace getFilePathService() { return filePathService; } public void setFilePathService(FilePathServiceFace filePathService) { this.filePathService = filePathService; } @ResponseBody @RequestMapping(value = "path",method = {RequestMethod.GET,RequestMethod.POST}) public List<String> view(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("WEB-INF/view"); List<String> path = filePathService.path(); return path; } /* @RequestMapping(value = "picture",method = {RequestMethod.GET,RequestMethod.POST}) @ResponseBody public void getImagesId(HttpServletResponse rp) { List<String> path = filePathService.path(); for (String filePath : path) { File imageFile = new File(filePath); if (imageFile.exists()) { FileInputStream fis = null; OutputStream os = null; try { fis = new FileInputStream(imageFile); os = rp.getOutputStream(); int count = 0; byte[] buffer = new byte[1024 * 8]; while ((count = fis.read(buffer)) != -1) { os.write(buffer, 0, count); System.out.println("IOflush一次"); os.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); os.close(); System.out.println("IO关闭一次"); } catch (IOException e) { e.printStackTrace(); } } } } }*/ }

    第二步 前端ajax调用请求获取图片路径数组

    <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/22 Time: 11:51 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script> <script type="text/javascript"> if (top.location !== self.location) { top.location=self.location; } </script> </head> <body> <div id="shuang"> <button onclick="common_getPicFileList()" style="width:1666px; height:666px; background-color: #e4b9b9;text-align: center ">查看历史记录</button> </div> <script type="text/javascript"> /** *获取图片文件数组 */ function common_getPicFileList() { $.ajax({ //此处使用的是自己封装的JAVA类 url: "path", type: "POST", success: function (data) { if (!data.length) { alert("data出错"); return; } else { //获取到的图片数组处理逻辑方法 loadPicFormDB(data); } }, error: function (e) { console.log(e); console.log("获取文件list数组失败,请检查接口服务"); } }); } /** * 加载图片,将图片拼成html代码 * @param SJ_CODE 事件编号 */ function loadPicFormDB(data) { var pichtml = ""; for (var i = 0; i < data.length; i++) { var src =data[i]; var html1 = '<li><a href="'+ src + '" rel="lightbox" title="' + data[i] + '" target="_blank">' + '<img οnlοad="AutoResizeImage(800,450,this)" src="view/' + src + '"></a><span>' + data[i] + '</span></li>'; pichtml += html1; //scrollPic(); } ; /* alert(pichtml)*/ showPic(pichtml); } /** * 按比例缩小图片 * @param maxWidth * @param maxHeight * @param objImg * @constructor */ function AutoResizeImage(maxWidth, maxHeight, objImg) { var img = new Image(); img.src = objImg.src; var hRatio; var wRatio; var Ratio = 1; var w = img.width; var h = img.height; wRatio = maxWidth / w; hRatio = maxHeight / h; if (maxWidth == 0 && maxHeight == 0) { Ratio = 1; } else if (maxWidth == 0) { // if (hRatio < 1) Ratio = hRatio; } else if (maxHeight == 0) { if (wRatio < 1) Ratio = wRatio; } else if (wRatio < 1 || hRatio < 1) { Ratio = (wRatio <= hRatio ? wRatio : hRatio); } if (Ratio < 1) { w = w * Ratio; h = h * Ratio; } objImg.height = h; objImg.width = w; } var baseText = null; /** 拼装替换html内容给DIV */ function showPic(pichtml){ var popUp = document.getElementById("shuang"); popUp.innerHTML = pichtml } </script> </body> </html>
    Processed: 0.037, SQL: 9