广告
返回顶部
首页 > 资讯 > 精选 >基于Springboot+vue如何实现图片上传至数据库并显示
  • 807
分享到

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

2023-07-06 11:07:43 807人浏览 八月长安
摘要

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

这篇文章主要讲解了“基于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

    @Datapublic 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类

    @Configurationpublic 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如何实现图片上传至数据库并显示这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

    --结束END--

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

    本文链接: https://www.lsjlt.com/news/357875.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作