SpringBoot vue图片上传不能立即回显问题解决

Posted java李杨勇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot vue图片上传不能立即回显问题解决相关的知识,希望对你有一定的参考价值。

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

解决方法:配置静态资源路径访问。配置虚拟路径。

后端上传文件代码:

@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);
    

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

以上是关于SpringBoot vue图片上传不能立即回显问题解决的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot+Vue+token实现(表单+图片)上传图片地址保存到数据库。上传图片保存位置自己定义图片可以在前端回显)

vue+Springboot上传oss阿里云并回显到前端页面

vue+Springboot上传oss阿里云并回显到前端页面

vue+Springboot上传oss阿里云并回显到前端页面

springboot项目图片上传,回显;使用外部静态资源路径回显图片

springboot项目图片上传,回显;使用外部静态资源路径回显图片