新建下面的类
package com.java456.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 图片绝对地址与虚拟地址映射 */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //文件磁盘图片url 映射 //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径 registry.addResourceHandler("/upload_image_01/**").addResourceLocations("file:"+ MyUtil.uploadPath); //registry.addResourceHandler("/userImage/**").addResourceLocations("file:D:\\userImages\\"); } }
配置文件添加下面
uploadPath=D://WebUploadFile/sut_upload/ /home/apache-tomcat-8.5.29/webapps/ROOT/ linux服务这样配置。 uploadPath=D://idea_space/qr_code/src/main/webapp/
上传文件接口修改如下。
/** * /admin/blog/add_cropper_image * imgData= data:image/png;base64,iVBORw0KGgoAAAiVBORw0KGgoAAAiVBORw0KGgoAAA后面非常多的字符,就是imgData */ @ResponseBody @RequestMapping("/add_cropper_image") public JSONObject add_cropper_image(@RequestParam(value = "imgData", required = false) String imgData, HttpServletResponse response, HttpServletRequest request) throws Exception { JSONObject result = new JSONObject(); //取得根目录带d://dxxxxx/tomcat/ruzhou/ //String webPath = request.getServletContext().getRealPath(""); String webPath = MyUtil.uploadPath; // D://WebUploadFile/dangan_upload/ String uploadFile = "/static/upload_image/stu_cover/" + DateUtil.formatDate(new Date(), "yyyyMMdd") + "/"; String fileName = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".jpg"; //调用产生文件夹的方法 FileUtil.makeDirs(webPath + uploadFile); imgData = imgData.replace("data:image/png;base64,", ""); Base64Util.GenerateImage(imgData, webPath + uploadFile + fileName); result.put("success", true); result.put("path", "/upload_image_01"+uploadFile + fileName); return result; }
public class MyUtil { //上传文件路径 从配置文件 初始化。 public static String uploadPath = "";
configservice
@Value("${uploadPath}") private String uploadPath; @Override public void init_properties() { MyUtil.uploadPath = uploadPath; }
configService.init_properties();
配置文件改成这样。 uploadPath=D://idea_space/stu_info_manage/src/main/webapp/
之前的图片路径,
/static/upload_image/blog_cover/20240324/20240324113545.jpg
改成/upload_image_01/static/upload_image/blog_cover/20240324/20240324113545.jpg
就可以使用了。
这个就相当于是,upload_image_01这个路径 ,会到webapp下面找去找,static刚好和webapp目录对应上。
这个有个问题 就是删除会出问题。
删除就路径就是。
D://idea_space/stu_info_manage/src/main/webapp/upload_image_01/static/upload_image/blog_cover/20240324/20240324113545.jpg
实际情况就是,webapp下面没有upload_image_01
站长微信:xiaomao0055
站长QQ:14496453