验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

怎么用Springboot+vue实现图片上传至数据库并显示

阅读:411 来源:乙速云 作者:代码code

怎么用Springboot+vue实现图片上传至数据库并显示

      一、前端设置

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

      
         
         
       
      
      修改

      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 {
      }

      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:StudyMyAdminscr

      三、显示图片

      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'
    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>