直接上代码吧
package com.ydx.emms.datapro.controller; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.io.File; /** * @Description: 通过ip和端口直接查看图片 * @param * @author zlw * @date 2024/9/4 15:09 */ @Configuration public class TPicController implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //虚拟url路径 registry.addResourceHandler("/file/**") .addResourceLocations("file:" + System.getProperty("user.dir").replace(File.separatorChar, '/') + "/file/"); //真实本地路径 } }
访问:http://127.0.0.1:端口/file/1.jpg
补充:从一个文件夹移动某一个文件到另一个文件夹
@RequestMapping(value = "/moveAlarmPic") Result moveAlarmPic(HttpServletRequest request) { // 获取请求参数 Map<String, Object> params = ParamUtil.getParams(request); String ip = MapUtils.getString(params, "ip"); String time = MapUtils.getString(params, "time"); // 参数判断 if (ParamUtil.isOneEmpty(ip, time)) { return new Result("rest_ACK", Result.Code.ParamError.value(), false, "参数不正确,必填参数有为空"); } else { //在告警文件夹下创建指定目录 makeDir(ip); //移动指定的图片 // 源文件路径 Path sourcePath = Paths.get(System.getProperty("user.dir") + "/pic/" + ip+"/"+time+".jpg"); Path sourcePathCsv = Paths.get(System.getProperty("user.dir") + "/pic/" + ip+"/"+time+".csv"); // 目标文件夹路径 Path destinationPath = Paths.get(System.getProperty("user.dir").replace(File.separatorChar, '/') + "/file/"+ip); // 目标文件完整路径 Path targetPath = destinationPath.resolve(sourcePath.getFileName()); Path targetPathCsv = destinationPath.resolve(sourcePathCsv.getFileName()); try { // 复制图片 Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); //复制矩阵 Files.copy(sourcePathCsv, targetPathCsv, StandardCopyOption.REPLACE_EXISTING); System.out.println("文件复制成功!"); return new Result("rest_ACK", Result.Code.Success.value(), true); } catch (IOException e) { System.out.println("文件复制失败: " + e.getMessage()); return new Result("rest_ACK", Result.Code.Success.value(), false); } } }
/** * @param * @Description: 指定目录下创建文件夹 * @author zlw * @date 2024/7/26 14:06 */ public void makeDir(String dirName) { // 指定要创建的文件夹路径 String directoryPath = System.getProperty("user.dir").replace(File.separatorChar, '/') + "/file/"+dirName; // 创建File对象 File dir = new File(directoryPath); // 如果文件夹不存在,则创建文件夹 if (!dir.exists()) { boolean result = dir.mkdir(); if (result) { System.out.println("文件夹创建成功:" + directoryPath); } else { System.out.println("文件夹创建失败:" + directoryPath); } } else { System.out.println("文件夹已存在:" + directoryPath); } }