SpringBoot + Vue 头像上传案例
头像上传
前言
后台系统一般会有用户个人信息的模块,为了增强用户的体验度,系统会开放自定义头像的功能,让用户可以上传自定义图片替代默认的系统头像。本文将通过SpringBoot+Vue来具体实现。
前端
<template>
<div><span style="margin-left: 160px" class="el-dropdown-links"><el-uploadaction="/sysUser/updateUrl":data="userForm.uid":show-file-list="false":on-success="onSuccess":before-upload="beforeUpload"><img title="点击修改头像" :src="valueUrl"/></el-upload></span></div>
</template><script>export default {name: "index",data() {return {userForm: {//添加数据uid: "1",userName: "userAdmin",password: "123456",nickName: "李四",sex: "",avatar: "",phoneNumber: "456421",email: "295@qq.com",userState: 1,userDate: ""},valueUrl: '/image/abc-20220531052328174.jpg',}},methods: {// 上传图片beforeUpload(file) {if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {this.$notify.warning({title: '警告',message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'});return false;}},// 上传图片回显onSuccess(res, file) {if (file.response.code == 500) {this.$message({type: 'error',message: file.response.message});} else {this.$message({type: 'success',message: file.response.message});console.log("--1--",file);// this.valueUrl = URL.createObjectURL(file.raw);console.log("--2--",this.valueUrl);// blob:http://localhost/ec6f040b-84b4-446a-9dd4-259b5f83789e// this.$EventBus.$emit("switchTab",file.raw);window.sessionStorage.setItem('avatar', file.response.obj);}},}}
</script><style>.el-dropdown-links {display: flex;text-align: center;line-height: 50px;}.el-dropdown-links img {width: 100px;height: 100px;border-radius: 50px;}</style>
后端
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" +" ''-' `'-' `-..-' ");}@Beanpublic 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 {@Overridepublic 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 {/*** 服务对象*/@Resourceprivate 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 头像上传案例相关推荐
- springboot+vue实现上传头像文件到阿里云对象存储oss
在阿里云oss上创建一个bucket,获取四个信息: 编写工具类,提供对外调用四个信息的方法: //当项目一启动,就执行接口的方法,读取配置文件内容 @Component public class C ...
- java(Vue+SpringBoot)实现头像上传功能
java实现文件上传功能 网上的其他方法繁琐复杂 不易理解,我总结了下面这种方法,适用于任何技术中,比如Vue+SpringBoot等等..不废话,上代码: 前端代码: <form method ...
- vue 头像上传裁剪功能
1,第一步安装vue-cropper cnpm install vue-cropper 2,在main.js引用 import VueCropper from 'vue-cropper'; Vue.u ...
- SpringBoot vue图片上传不能立即回显问题解决
最开始项目是放在eclipse之中的.springboot项目默认把静态的文件加载到classpath的目录下的.而此时我们上传的图片并没有传入启动了的项目当中去.所以明明路径是对的.却访问不了.在项 ...
- 头像上传案例 (上传文件)
// 步骤: /*文件上传思路总结 1. 给file表单注册onchange事件 * 当用户选择图片之后执行 2. 获取用户选择的文件 *let file= this.files[0] 3. 使用Fo ...
- springboot+vue图片上传显示
1.启动类 @Override//图片上传的public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.ad ...
- Vue头像上传,裁剪
安装:npm install vue-image-crop-upload --save (作为开发依赖安装) 使用:import myUpload from 'vue-image-crop-uploa ...
- vue 移动端头像裁剪_vue头像上传裁剪组件_一个漂亮的Vue组件,用于图像裁剪和上传...
vue头像上传裁剪组件 vue-image-crop-upload (vue-image-crop-upload) A beautiful vue component for image crop a ...
- 基于 springboot + vue 的 element-ui 的 upload 组件头像上传功能
基于 springboot + vue 的 element-ui 的 upload 组件头像上传 为了方便我们自己本地测试使用,我们将文件上传至自己电脑的磁盘中,由于项目是前后端分离的,所以我们会直接 ...
最新文章
- jQuery源码-jQuery.fn.each jQuery.each
- (0098)iOS开发之应用间的分享系列(3)
- vrrp广播风暴_企业园区网MSTP+VRRP组合
- 彩色图像--色彩空间 YIQ 、YUV 、YCbCr 、YC1C2 和I1I2I3
- linux 查找大文件
- 使用 MWC V2.5 中的 MPU6050中的DMP进行计算姿态(转载)
- Dephi7程序设计与开发技术大全(求是科技)
- [Windows]查看运行进程的参数【wmic】
- LeetCode 面试题 03 数组中重复的数字
- ubuntu server 12.04中文显示不完整
- Confluence 6 针对合并完全失败的内容重新运行合并
- 1月8日 官方ros.org太慢,配置中科院ros镜像源 关于解决Ubuntu 14.04安装ros提示校验错误解决
- POJ 3660 Cow Contest(Floyd求传递闭包(可达矩阵))
- SSM项目实战:学生学籍管理系统
- 解决Google Chrome添加快捷方式图标模糊
- 运营管理模型对计算机软件,生产与运作管理
- dede taglist模板中调用自定义字段
- OCR 图像智能字符识别技术
- win7 黑屏之感叹
- C语言feof()函数的使用
热门文章
- 用百行Python代码写一个关于德州扑克的类
- updog:一款局域网传输文件的软件
- js防抖、节流(立即执行/非立即执行 + 立即取消等待)
- javaweb+themeleaf+Tomcat学习——org.thymeleaf.exceptions.TemplateProcessingException
- PLC单个自复位按钮控制指示灯的6种方法,总有一种适合你,学到就是赚到。
- CollageIt 3 Pro for mac(拼贴精灵3专业版)
- python绘图之使用matplotlib连接两个点
- 浏览器安全之CSRF跨站请求伪造
- matlab cnn 局部最大值,Matlab实现CNN(一)
- php输出圆周率100位,圆周率1500多位