基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能
技術(shù)棧介紹
Spring Boot:一個基于Spring框架的開源項(xiàng)目,用于簡化Spring應(yīng)用的初始搭建以及開發(fā)過程。它通過提供默認(rèn)配置減少開發(fā)中的配置工作,使得開發(fā)者能夠快速啟動和部署Spring應(yīng)用。
Vue.js:一個漸進(jìn)式JavaScript框架,用于構(gòu)建用戶界面。Vue的核心庫只關(guān)注視圖層,易于上手,同時也能夠配合其他庫或現(xiàn)有項(xiàng)目使用。Vue.js以其輕量級、高效性和靈活性而廣受歡迎。
后端實(shí)現(xiàn)
后端使用Spring Boot框架,通過@RestController注解定義一個控制器UploadController,提供/upload端點(diǎn)處理文件上傳請求。代碼中使用了MultipartFile來接收上傳的文件,并將其保存到服務(wù)器的指定目錄。
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
代碼注釋
@RestController
public class UploadController {
@Operation(summary = "上傳圖片到本地")
@PostMapping("/upload")
public String upload(MultipartFile file) {
if (file.isEmpty()) {
return "圖片為空";
}
String originalFilename = file.getOriginalFilename();
String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
assert originalFilename != null;
String fileNameSuffix = "." + originalFilename.split("\\.")[1];
String fileName = fileNamePrefix + fileNameSuffix;
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";
String pre = applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() + "\\spring-ui\\src\\assets\\avatar\\";
String path = pre + fileName;
try {
file.transferTo(new File(path));
String replace = path.replace(applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() + "\\spring-ui\\src", "/src");
return replace.replace("\\", "/");
} catch (IOException e) {
e.printStackTrace();
}
return "圖片上傳失敗";
}
}
前端實(shí)現(xiàn)
前端使用Vue.js框架,通過封裝axios請求和全局配置,實(shí)現(xiàn)與后端的通信。同時,使用Vite作為構(gòu)建工具,配置代理解決跨域問題。
代碼注釋
全局配置封裝
// config/index.ts
export const baseURL = '/api'; // 基礎(chǔ)URL
export const timeout = 10000; // 請求超時時間
export const headers = { 'X-Custom-Header': 'foobar' }; // 自定義請求頭
Axios二次封裝
// request/index.ts
const request = axios.create({
// 配置axios實(shí)例
baseURL,
timeout,
headers
});
// 添加請求和響應(yīng)攔截器
request.interceptors.request.use((config) => {
// 請求攔截器邏輯
return config;
}, (error) => {
// 響應(yīng)攔截器邏輯
return Promise.reject(error);
});
Api接口請求
//api/index.ts
import * as common from '@/api/common'
import * as user from '@/api/user'
const api = {
common,
user,
}
export default api;
//api/common.ts
import request from "@/request";
// 響應(yīng)接口
export interface UploadRes {}
/**
* 上傳圖片到本地
* @param {string} file
* @returns
*/
export function upload(file: object): Promise<UploadRes> {
return request.post(`/upload`, file);
}
//api/user.ts
import request from "@/request";
// 參數(shù)接口
export interface UpdateUserParams {
id?: number;
name?: string;
sex?: string;
age?: number;
pic?: string;
acc?: string;
pwd?: string;
phone?: string;
email?: string;
dept?: string;
post?: string;
status?: string;
createBy?: string;
createTime?: string | unknown;
updateBy?: string;
updateTime?: string | unknown;
remark?: string;
}
// 響應(yīng)接口
export interface UpdateUserRes {
message: string;
success: boolean;
code: number;
data: Record<string, unknown>;
}
/**
* 修改-賬號
* @param {object} params $!{table.comment}
* @param {number} params.id
* @param {string} params.name 姓名
* @param {string} params.sex 性別
* @param {number} params.age 年齡
* @param {string} params.pic 頭像
* @param {string} params.acc 賬號
* @param {string} params.pwd 密碼
* @param {string} params.phone 電話號碼
* @param {string} params.email 電子郵件
* @param {string} params.dept 用戶部門
* @param {string} params.post 用戶崗位
* @param {string} params.status 狀態(tài)(0正常 1停用)
* @param {string} params.createBy 創(chuàng)建者
* @param {object} params.createTime 創(chuàng)建時間
* @param {string} params.updateBy 更新者
* @param {object} params.updateTime 更新時間
* @param {string} params.remark 備注
* @returns
*/
export function updateUser(params: UpdateUserParams): Promise<UpdateUserRes> {
return request.post(`/userEntity/update`, params);
}
解決CORS跨域問題
// vite.config.ts
export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://localhost:9090/", // 后端服務(wù)地址
changeOrigin: true, // 是否改變源
rewrite: (path) => path.replace(/\/api/, ""), // 重寫路徑
},
},
},
});
業(yè)務(wù)處理代碼
<template>
<!-- 上傳組件和提示信息 -->
<el-upload drag :show-file-list="false" :limit="1" action="#" :auto-upload="false" accept=".png"
:on-change="handleChanges">
<el-icon class="el-icon--upload">
<upload-filled/>
</el-icon>
<div class="el-upload__text">
<em> 點(diǎn)擊 </em> 或<em> 拖動文件 </em>上傳
</div>
<template #tip>
<div class="el-upload__tip">
僅支持 jpg/png 格式文件大小小于 2MB
</div>
</template>
</el-upload>
</template>
<script setup>
import { ref } from "vue";
import api from "@/api";
// 響應(yīng)式引用,用于存儲用戶信息
const user = ref({});
// 生命周期鉤子,初始化時獲取用戶信息
onMounted(() => {
user.value = JSON.parse(localStorage.getItem("user"));
});
// 處理文件變化,上傳文件并更新用戶信息
//修改頭像
const handleChanges = (file) => {
if (file.raw.type !== 'image/png') {//限制文件類型
ElMessage.error({message: "只能上傳png格式的文件", grouping: true, showClose: true});
return false;
}
if (file.raw.size / 1024 / 1024 > 5) {
ElMessage.error('文件大于 5MB!')
return false;
}
const param = new FormData();
param.append('file', file.raw);
api.common.upload(param).then((res: any) => {
if (res !== null) ElMessage.success("上傳成功");
if (res === null) ElMessage.error("上傳失敗");
api.user.updateUser({id: user.value.id, pic: res}).then((res: any) => {
api.user.selectUserByAcc(user.value.acc).then((res: any) => {
//更新緩存
localStorage.setItem("user", JSON.stringify(res.data));
//更新左側(cè)描述列表
user.value = res.data;
})
})
})
};
</script>
<style scoped>
:deep(.el-descriptions__label) {
min-width: 60px !important;
}
</style>
功能演示
在文章的最后,我們將展示上傳頭像功能的完整流程,包括前端的上傳界面、后端的文件保存邏輯,以及成功上傳后的頭像回顯效果。


結(jié)語
通過本文的介紹,我們學(xué)習(xí)了如何使用Spring Boot和Vue.js實(shí)現(xiàn)一個完整的頭像上傳與回顯功能。這種前后端分離的開發(fā)模式不僅提高了開發(fā)效率,也使得系統(tǒng)更加模塊化和易于維護(hù)。隨著技術(shù)的不斷進(jìn)步,我們期待未來能夠有更多類似的協(xié)同工作解決方案出現(xiàn),以滿足不同場景下的開發(fā)需求。
以上就是基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Vue頭像上傳與回顯的資料請關(guān)注腳本之家其它相關(guān)文章!
- 使用Springboot+Vue實(shí)現(xiàn)文件上傳和下載功能
- Vue?+?SpringBoot?實(shí)現(xiàn)文件的斷點(diǎn)上傳、秒傳存儲到Minio的操作方法
- springboot+vue實(shí)現(xiàn)阿里云oss大文件分片上傳的示例代碼
- Java實(shí)現(xiàn)大文件的分片上傳與下載(springboot+vue3)
- springboot整合vue2-uploader實(shí)現(xiàn)文件分片上傳、秒傳、斷點(diǎn)續(xù)傳功能
- 利用Springboot+vue實(shí)現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的全過程
- Vue+Element+Springboot圖片上傳的實(shí)現(xiàn)示例
- Springboot+Vue-Cropper實(shí)現(xiàn)頭像剪切上傳效果
- springboot + vue+elementUI實(shí)現(xiàn)圖片上傳功能
相關(guān)文章
MyBatis自定義TypeHandler如何解決字段映射問題
這篇文章主要介紹了MyBatis自定義TypeHandler如何解決字段映射問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
springboot中的controller參數(shù)映射問題小結(jié)
這篇文章主要介紹了springboot中的controller參數(shù)映射問題小結(jié),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-12-12
JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn)
這篇文章主要介紹了JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Java實(shí)戰(zhàn)之實(shí)現(xiàn)OA辦公管理系統(tǒng)
這篇文章主要介紹了如何通過Java實(shí)現(xiàn)OA辦公管理系統(tǒng),文章采用到了JSP、JQuery、Ajax等技術(shù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-02-02
Springboot @Configuration @bean注解作用解析
這篇文章主要介紹了springboot @Configuration @bean注解作用解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02
Java使用pulsar-flink-connector讀取pulsar catalog元數(shù)據(jù)代碼剖析
這篇文章主要介紹了Java使用pulsar-flink-connector讀取pulsar catalog元數(shù)據(jù)代碼剖析,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08
Java中MyBatis傳入?yún)?shù)parameterType問題
這篇文章主要介紹了Java中MyBatis傳入?yún)?shù)parameterType問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
java去除集合中重復(fù)元素示例分享 java去除重復(fù)
這篇文章主要介紹了java去除集合中重復(fù)元素示例,大家參考使用吧2014-01-01

