SpringBoot + Vue 头像上传案例

头像上传

前言

后台系统一般会有用户个人信息的模块,为了增强用户的体验度,系统会开放自定义头像的功能,让用户可以上传自定义图片替代默认的系统头像。本文将通过SpringBoot+Vue来具体实现。

前端







后端

package com.cs.admin;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

@SpringBootApplication
@MapperScan("com.cs.admin.mapper")
public class AdminApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙  项目启动成功   ლ(´ڡ`ლ)゙  \n" +
                           " .-------.       ____     __        \n" +
                           " |  _ _   \\      \\   \\   /  /    \n" +
                           " | ( ' )  |       \\  _. /  '       \n" +
                           " |(_ o _) /        _( )_ .'         \n" +
                           " | (_,_).' __  ___(_ o _)'          \n" +
                           " |  |\\ \\  |  ||   |(_,_)'         \n" +
                           " |  | \\ `'   /|   `-'  /           \n" +
                           " |  |  \\    /  \\      /           \n" +
                           " ''-'   `'-'    `-..-'              ");
    }
    
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //允许上传的文件最大值
        factory.setMaxFileSize(DataSize.parse("50MB")); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("50MB"));
        return factory.createMultipartConfig();
    }
    
}
package com.cs.admin.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* 配置静态资源访问
*/
@Configuration
public class MvcWebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**")//请求路径,相对路径
            //转发路径,绝对路径
            .addResourceLocations("file:" +
                                  System.getProperty("user.dir") +
                                  System.getProperty("file.separator") +
                                  "src/main/resources/static/image/");
        
    }
}
package com.example.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * (SysUser)表控制层
 *
 * @author makejava
 * @since 2022-05-23 17:33:13
 */
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;

    @PostMapping("updateUrl")
    public Result setAvatar(MultipartFile file, int uid) throws IOException {
        //判断图片是否为空
        if (file.isEmpty()) {
            return Result.error().message("上传图片为空");
        }
        //获取图片名称
        String imgName = file.getOriginalFilename();
        //获取图片后缀
        String ss = imgName.substring(imgName.lastIndexOf("."));
        //判断图片格式是否正确
        if (!ss.equals(".jpg") && !ss.equals(".jpeg") && !ss.equals(".png")) {
            return Result.error().message("图片格式不正确");
        }
        //获取图片前缀 + 时间 + 图片后缀
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
        String nowStr = imgName.substring(0, imgName.lastIndexOf(".")) + "-" + format.format(date);
        //进行拼接,重新获取图片名称
        String fileName = nowStr + imgName.substring(imgName.lastIndexOf("."));
        //图片的路径
        String names = "/image/" + fileName;
        //获取图片存放的路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "src\\main\\resources\\static" + File.separator + "image";
        File file1 = new File(filePath);
        //判断是否有文件夹,没有就创建一个文件夹
        if (!file1.exists()) {
            // file1.mkdir();
            file1.getParentFile().mkdir();
            file1.getAbsoluteFile().mkdir();
        }
        //把图片存放进去
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        file.transferTo(dest);
        //把图片路径存放到数据库
        SysUser sysUser = new SysUser();
        sysUser.setUid(uid);
        sysUser.setAvatar(names);
//        sysUserService.save(sysUser);
        sysUserService.updateById(sysUser);
        return Result.ok().data(names);
    }
}

你可能感兴趣的:(SpringBoot,vue.js,spring,boot,前端)