溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示

發(fā)布時間:2023-04-20 09:40:32 來源:億速云 閱讀:378 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下怎么用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

    一、前端設(shè)置

    前端是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在這里可以隨便設(shè)置,因為在后面有 :http-request 去自己設(shè)置請求,注意由于是自己寫請求需要 :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;
        },
    //這里是自定義發(fā)送請求
        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數(shù)據(jù)
           this.$store.state.menu.currentUserInfo=res.data.data.backUser
           //這里返回的是頭像的url
           this.imageUrl = res.data.data.backUser.avatar
         })
       },
       //觸發(fā)請求
        submitUpload(){
       this.$refs.upload.submit();
     	}
    }

    在上面代碼中有一個坑 f.file ,我看了許多博客,發(fā)現(xiàn)有些博客只有 f 沒有 .file 導(dǎo)致出現(xiàn)401、505錯誤。

    二、后端代碼

    1.建立數(shù)據(jù)庫

    怎么用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示

    這里頭像avatar是保存的上傳圖片的部分url

    2.實體類、Mapper

    實體類:

    采用mybatis plus

    @Data
    public class SysUser extends BaseEntity{
    //這里的BaseEntity是id,statu,created,updated數(shù)據(jù)
        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.接受請求,回傳數(shù)據(jù)

        @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,采用隨機數(shù),保證每個圖片的url不同
            UUID uuid = UUID.randomUUID();
            //重新拼接文件名,避免文件名重名
            int index = fileName.indexOf(".");
            String newFileName ="/avatar/"+fileName.replace(".","")+uuid+fileName.substring(index);
            //存入數(shù)據(jù)庫,這里可以加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.后端配置

    實現(xiàn)前端Vue :scr 更具url顯示頭像圖片,則必須設(shè)置WebMVC中的靜態(tài)資源配置

    建立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("靜態(tài)資源獲取");
        }
    }

    這樣就可是顯示頭像圖片了

    2.前端配置

    注意跨域問題以及前面的全局地址變量

    vue.config.js文件(若沒有則在scr同級目錄下創(chuàng)建):

    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實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI