vue+springboot实现图片的上传及回显失败问题的解决

vue+springboot实现图片的上传及回显失败问题的解决

<div class="upload">
	<input type="file" id="saveImage" accept="image/png,image/gif,image/jpeg" ref="new_image">
    <input type="text" hidden id="hiddenContent" v-model="picAddress">
    <input type="button" value="上传头像" @click="submitPhoto()"/>
    <div class="photo">
        <img :src="url" class="img" >
    </div>
</div>

submitPhoto():

submitPhoto() {
	let self = this;
    if (self.$refs.new_image.files.length !== 0) {
    	let formData = new FormData();
        formData.append('image_data', self.$refs.new_image.files[0]);
            this.$axios.post('api/user/uploadPhoto', formData)
            .then(res => {
                let imgUrl = res.data;
                this.uploadPhotot(imgUrl);
            })
     }
},

这里的imgUrl就是图片的路径,可以在浏览器中直接访问得到的。
uploadPhoto就是把图片路径及其他数据存到数据库的方法。
springboot中这样写:

@PostMapping("/uploadPhoto")
@ApiOperation(value = "上传头像", notes = "上传头像")
public String uploadPhoto(@RequestParam(name = "image_data", required = false) MultipartFile file) throws IOException {
	// 文件上传
	String imageName = file.getOriginalFilename();
	String newCompanyImagePath = "";
	if (!file.isEmpty()) {
		try {
			//D:\\Program Files (x86)\\workspace-spring-tool-suite-4-4.6.2.RELEASE\\csi\\src\\main\\resources\\static\\img\\
			newCompanyImagePath = "D:\\Program Files (x86)\\workspace-spring-tool-suite-4-4.6.2.RELEASE\\csi\\src\\main\\resources\\static\\img\\"
						+ imageName;

			File newFile = new File(newCompanyImagePath);
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "图片上传失败!";
		} catch (IOException e) {
			e.printStackTrace();
			return "图片上传失败!";
		}
	}
	String imagePath = "http://localhost:8888/static/img/" + imageName;
	return imagePath;
}

上面的newCompanyImagePath 就是该项目中存放图片的文件夹的绝对路径
项目结构如下:
在这里插入图片描述
还有一个问题就是新上传一张图片之后,回显会失败,要刷新后端项目img文件夹,重新运行项目才能显示出来,怎么解决这个问题呢?
这里我们可以通过虚拟路径映射的方法来解决。
在后端项目中添加一个类:

//新增加一个类用来添加虚拟路径映射
@Configuration
public class MyPicConfig implements WebMvcConfigurer{
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/img/**")
        .addResourceLocations("file:D:/Program Files (x86)/workspace-spring-tool-suite-4-4.6.2.RELEASE/csi/src/main/resources/static/img/");
    }
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值