基于Springboot+vue如何实现图片上传至数据库并显示

发布时间:2023-05-19 16:02:54 作者:iii
来源:亿速云 阅读:78

这篇文章主要讲解了“基于Springboot+vue如何实现图片上传至数据库并显示”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“基于Springboot+vue如何实现图片上传至数据库并显示”吧!

一、前端设置

前端是Vue + Element-UI 采用el-upload组件(借鉴官方)上传图片:

<el-upload
     ref="upload"
     class="avatar-uploader"
     action="/setimg"
     :http-request="picUpload"
     :show-file-list="false"
     :auto-upload="false"
     :on-success="handleAvatarSuccess"
     :before-upload="beforeAvatarUpload">
   <img v-if="$hostURL+imageUrl" :src="$hostURL+imageUrl" class="avatar">
   <i v-else class="el-icon-plus avatar-uploader-icon"></i>
 </el-upload>

<el-button type="primary" @click="submitUpload">修改</el-button>

action在这里可以随便设置,因为在后面有 :http-request 去自己设置请求,注意由于是自己写请求需要 :auto-upload=“false” ,并且由于是前后端连接要解决跨域问题,所以在 $hostURL+imageUrl 定义了一个全局变量:

//在main.js中
	Vue.prototype.$hostURL='http://localhost:8082'

在methods中:

methods:{
//这里是官方的方法不变
	handleAvatarSuccess(res, file){
	      this.imageUrl = URL.createObjectURL(file.raw);
	},
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
//这里是自定义发送请求
    picUpload(f){
     let params = new FormData()
     //注意在这里一个坑f.file
     params.append("file",f.file);
     this.$axios({
       method:'post',
       //这里的id是我要改变用户的ID值
       url:'/setimg/'+this.userForm.id,
       data:params,
       headers:{
         'content-type':'multipart/form-data'
       }
     }).then(res=>{
     //这里是接受修改完用户头像后的JSON数据
       this.$store.state.menu.currentUserInfo=res.data.data.backUser
       //这里返回的是头像的url
       this.imageUrl = res.data.data.backUser.avatar
     })
   },
   //触发请求
    submitUpload(){
   this.$refs.upload.submit();
 	}
}

在上面代码中有一个坑 f.file ,我看了许多博客,发现有些博客只有 f 没有 .file 导致出现401、505错误。

二、后端代码

1.建立数据库

基于Springboot+vue如何实现图片上传至数据库并显示

这里头像avatar是保存的上传图片的部分url

2.实体类、Mapper

实体类:

采用mybatis plus

@Data
public class SysUser extends BaseEntity{
//这里的BaseEntity是id,statu,created,updated数据
    private static final Long serialVersionUID = 1L;

    @NotBlank(message = "用户名不能为空")
    private String username;

//    @TableField(exist = false)
    private String password;
    @NotBlank(message = "用户名称不能为空")
    private String name;
    //头像
    private String avatar;

    @NotBlank(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确")
    private String email;
    private String tel;
    private String address;
    @TableField("plevel")
    private Integer plevel;
    private LocalDateTime lastLogin;
}
@Mapper
@TableName("sys_user")
public interface SysUserMapper extends BaseMapper<SysUser> {
}
3.接受请求,回传数据
    @Value("${file.upload-path}")
    private String pictureurl;
    @PostMapping("/setimg/{id}")
    public Result setImg(@PathVariable("id") Long id, @RequestBody MultipartFile file){
        String fileName = file.getOriginalFilename();
        File saveFile = new File(pictureurl);
        //拼接url,采用随机数,保证每个图片的url不同
        UUID uuid = UUID.randomUUID();
        //重新拼接文件名,避免文件名重名
        int index = fileName.indexOf(".");
        String newFileName ="/avatar/"+fileName.replace(".","")+uuid+fileName.substring(index);
        //存入数据库,这里可以加if判断
        SysUser user = new SysUser();
        user.setId(id);
        user.setAvatar(newFileName);
        sysUserMapper.updateById(user);
        try {
            //将文件保存指定目录
            file.transferTo(new File(pictureurl + newFileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("保存成功");
        SysUser ret_user = sysUserMapper.selectById(user.getId());
        ret_user.setPassword("");
        return Result.succ(MapUtil.builder()
                .put("backUser",ret_user)
                .map());
    }

yml文件中图片的保存地址:

file:
  upload-path: D:\Study\MyAdmin\scr

三、显示图片

1.后端配置

实现前端Vue :scr 更具url显示头像图片,则必须设置WebMVC中的静态资源配置

建立WebConfig类

@Configuration
public class WebConfig implements WebMvcConfigurer{
    private String filePath = "D:/Study/MyAdmin/scr/avatar/";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/avatar/**").addResourceLocations("file:"+filePath);
        System.out.println("静态资源获取");
    }
}

这样就可是显示头像图片了

2.前端配置

注意跨域问题以及前面的全局地址变量

vue.config.js文件(若没有则在scr同级目录下创建):

module.exports = {
    devServer: {
        // 端口号
        open: true,
        host: 'localhost',
        port: 8080,
        https: false,
        hotOnly: false,
        // 配置不同的后台API地址
        proxy: {
            '/api': {
            //后端端口号
                target: 'http://localhost:8082',
                ws: true,
                changOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },
        before: app => {}
    }
}

main.js:

	axios.defaults.baseURL = '/api'

感谢各位的阅读,以上就是“基于Springboot+vue如何实现图片上传至数据库并显示”的内容了,经过本文的学习后,相信大家对基于Springboot+vue如何实现图片上传至数据库并显示这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 基于springboot和docker-java怎么实现对docker容器的动态管理和监控功能
  2. springboot应用实例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot vue 数据库

上一篇:如何使用springboot及vue实现垃圾分类管理系统

下一篇:vue怎么定义数组

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》