search
HomeJavajavaTutorialHow to use Springboot+vue to upload images to the database and display them

    1. Front-end settings

    The front-end is Vue Element-UI and uses the el-upload component (drawing from the official) to upload images:

    <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  class="avatar lazy"  src="/static/imghwm/default1.png"  data-src="$hostURL+imageUrl"  v-if="$hostURL+imageUrl" :  alt="How to use Springboot+vue to upload images to the database and display them" >
       <i v-else class="el-icon-plus avatar-uploader-icon"></i>
     </el-upload>
    
    <el-button type="primary" @click="submitUpload">修改</el-button>

    actionYou can set it casually here, because there is :http-request at the back to set the request yourself. Note that since you write the request yourself, you need :auto-upload="false" , and since the front-end and back-end connections need to solve cross-domain problems, a global variable is defined in $hostURL imageUrl:

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

    In methods:

    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();
     	}
    }

    There is a pitfall in the above code f.file. I read many blogs and found that some blogs only have f but not .file, resulting in 401 and 505 errors.

    2. Back-end code

    1. Establish database

    How to use Springboot+vue to upload images to the database and display them

    Here the avatar is the saved partial url of the uploaded image

    2. Entity class, Mapper

    Entity class:

    Using 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. Accept the request and return the data

        @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());
        }

    Save address of pictures in yml file:

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

    3. Display pictures

    1. Backend configuration

    Implement front-end Vue :scr If you want to display the avatar image in the url, you must set the static resource configuration in WebMVC

    Create the WebConfig class

    @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("静态资源获取");
        }
    }

    This way you can display the avatar image

    2. Front end Configuration

    Pay attention to cross-domain issues and the previous global address variable

    vue.config.js file (if not, create it in the same directory as 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;

    The above is the detailed content of How to use Springboot+vue to upload images to the database and display them. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment