直接上代码吧
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 {@Overridepublic 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);} }