解决SpringBoot + Vue图片上传后不立刻回显的问题

最近捣鼓一个放在eclipse上面的vue项目、最开始项目是放在eclipse中的、在文件处理上传的时候springboot项目默认把静态的文件加载到classpath的目录下的。而此时我们上传的图片并没有传入启动了的项目当中去、所以明明路径是对的、却访问不了、在项目重新启动之后项目会打成新的jar包、这个时候上一次上传的图片才会正常显示。

主要流程就是: 单击前端Vue文件上传按钮,在计算机中选择文件上传,并将该文件替换为所选文件

单击“上传”,通过文件流将图片上传到后台controller服务器。服务器将图片保存到指定的位置,我配置的是盘符路径、并生成指定的文件名称。如果上传成功,则返回新生成的文件名。

图片上传成功后,上传的图片将显示在成功、根据路径加载到页面

解决方法 :在application.ymlz中配置静态资源文件路径访问。配置虚拟路径。

virtuel:
  filePath: E:/jiaodaVideo/

后端controller上传文件代码:

@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file,String type) throws Exception {
		if (file.isEmpty()) {
			throw new EIException("上传文件不能为空");
		}
		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
		File upload = new File("D:/work/");
		if(!upload.exists()) {
		    upload.mkdirs();
		}
		String fileName = new Date().getTime()+"."+fileExt;
		File dest = new File(upload+"/"+fileName);
 
		file.transferTo(dest);
		if(StringUtils.isNotBlank(type) && type.equals("1")) {
			ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
			if(configEntity==null) {
				configEntity = new ConfigEntity();
				configEntity.setName("faceFile");
				configEntity.setValue(fileName);
			} else {
				configEntity.setValue(fileName);
			}
			configService.insertOrUpdate(configEntity);
		}
		return R.ok().put("file", fileName);
	}

File upload = new File(“D:/work/”);这里路径建议在yml里面配置、然后读取、因为我这是简单的毕业设计项目、所以就直接写死了。

配置WebMvcConfigurationSupport重写addResourceHandlers即可实现。

/**
 * springboot 2.0配置WebMvcConfigurationSupport之后,会导致默认配置被覆盖,要访问静态资源需要重写addResourceHandlers方法
*/
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/resources/")
        .addResourceLocations("classpath:/static/")
		.addResourceLocations("classpath:/upload/")
		.addResourceLocations("classpath:/admin/")
        .addResourceLocations("classpath:/front/")
        .addResourceLocations("classpath:/public/");
		registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/work/");
		super.addResourceHandlers(registry);
    }

最后上传和保存对象数据成功

image.png

问题解决。简单记录一下。


作者:java李杨勇
链接:SpringBoot vue图片上传不能立即回显问题解决 - 掘金