>  기사  >  Java  >  Springboot+vue를 사용하여 데이터베이스에 이미지를 업로드하고 표시하는 방법

Springboot+vue를 사용하여 데이터베이스에 이미지를 업로드하고 표시하는 방법

WBOY
WBOY앞으로
2023-05-12 09:52:052501검색

    1. 프런트 엔드 설정

    프런트 엔드는 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" alt="Springboot+vue를 사용하여 데이터베이스에 이미지를 업로드하고 표시하는 방법" >
       <i v-else class="el-icon-plus avatar-uploader-icon"></i>
     </el-upload>
    
    <el-button type="primary" @click="submitUpload">修改</el-button>

    action설정할 수 있습니다. : http- at the back request 요청을 직접 설정하세요. 요청을 직접 작성하므로 :auto-upload="false"가 필요합니다. -엔드 및 백엔드 연결은 도메인 간 문제를 해결해야 하며 전역 변수는 $hostURL+imageUrl에 정의되어 있습니다.

    //在main.js中
    	Vue.prototype.$hostURL=&#39;http://localhost:8082&#39;

    In 메소드:

    methods:{
    //这里是官方的方法不变
    	handleAvatarSuccess(res, file){
    	      this.imageUrl = URL.createObjectURL(file.raw);
    	},
        beforeAvatarUpload(file) {
          const isJPG = file.type === &#39;image/jpeg&#39;;
          const isLt2M = file.size / 1024 / 1024 < 2;
    
          if (!isJPG) {
            this.$message.error(&#39;上传头像图片只能是 JPG 格式!&#39;);
          }
          if (!isLt2M) {
            this.$message.error(&#39;上传头像图片大小不能超过 2MB!&#39;);
          }
          return isJPG && isLt2M;
        },
    //这里是自定义发送请求
        picUpload(f){
         let params = new FormData()
         //注意在这里一个坑f.file
         params.append("file",f.file);
         this.$axios({
           method:&#39;post&#39;,
           //这里的id是我要改变用户的ID值
           url:&#39;/setimg/&#39;+this.userForm.id,
           data:params,
           headers:{
             &#39;content-type&#39;:&#39;multipart/form-data&#39;
           }
         }).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 오류가 발생하는 것으로 나타났습니다.

    2. 백엔드 코드

    1. 데이터베이스 생성

    Springboot+vue를 사용하여 데이터베이스에 이미지를 업로드하고 표시하는 방법

    여기서 아바타는 업로드된 이미지의 저장된 부분 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

    3. 백엔드 구성

    프런트엔드 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: &#39;localhost&#39;,
            port: 8080,
            https: false,
            hotOnly: false,
            // 配置不同的后台API地址
            proxy: {
                &#39;/api&#39;: {
                //后端端口号
                    target: &#39;http://localhost:8082&#39;,
                    ws: true,
                    changOrigin: true,
                    pathRewrite: {
                        &#39;^/api&#39;: &#39;&#39;
                    }
                }
            },
            before: app => {}
        }
    }

    main.js:

    	axios.defaults.baseURL = &#39;/api&#39;

    위 내용은 Springboot+vue를 사용하여 데이터베이스에 이미지를 업로드하고 표시하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제