文章目錄
- 環境背景
- 最終效果
- 前端講解
- 左側模塊解析
- 右側上傳模塊解析
- 前端步驟
- 后端講解
- 代碼
- 前端
環境背景
- 若依前后端分離框架 + vue
- 最后邊附有代碼哦
最終效果
前端講解
左側模塊解析
- 1、左側表單使用el-form
注意:
1、prop出現的字段,需要保證是該類所具有的字段
2、點擊提交按鈕后,調用的是handleSubmit方法
右側上傳模塊解析
① v-if=“uploadedFileName” 如果對uploadedFileName不為空,該控件顯示
② v-model=“upload.open” 在vue2中會寫成 :visible.sync=“upload.open” ,在vue3中是不生效的,需要修改
③ 上傳文件限制,只能上傳1個
④ 前端限制,上傳的文件只能是pdf
前端步驟
-
1、在打開頁面時,通過 created() 的 this.fetchResumeData()來獲取數據
-
2、fetchResumeData通過await getResumeByUsername(username)來調用js的方法然后獲得數據,然后通過this.myResume=response.data填充
-
3、當點擊上傳簡歷按鈕時,會調用handleImport方法,然后更改upload的open屬性為true,這樣就顯示了上傳文件的對話框了
-
4、文件上傳完成后,會調用submitFileForm方法,開始上傳,同時調用upload中的url進行文件解析
-
5、上傳成功后,會調用handleFileSuccess方法,然后將內容填充
后端講解
- pom文件
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.26</version>
</dependency>
- controller層
@RequestMapping("/parsepdf")public AjaxResult parsePdf(@RequestParam("file") MultipartFile file) {try {// 保存文件到本地String filePath = PdfUtil.save(file);// 獲取 PDF 文件內容String content = PdfUtil.getContent(file.getInputStream());// 解析 PDF 內容并封裝為簡歷信息Map<String, String> map = PdfUtil.setResume(content,file.getName(),filePath);// 返回解析后的數據return AjaxResult.success(map);} catch (Exception e) {System.err.println(e.getMessage());return AjaxResult.error("文件解析失敗:" + e.getMessage());}}
-
pdf格式說明
需按照如下的格式,因為正則匹配的解析是這么來的,可以結合后邊的正則函數查看
-
PdfUtil類
package com.ruoyi.utils;import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class PdfUtil {/*** 將上傳的文檔保存到本地* @param file* @return* @throws IOException*/public static String save(MultipartFile file) throws IOException{String path = FileUploadUtils.upload(file);// 為什么是e?String realPath = path.substring(path.indexOf("e")+2);String baseDir = RuoYiConfig.getProfile();String filePath = baseDir + realPath;return filePath;}public static String getContent(InputStream inputStream) throws IOException {try (PDDocument document = PDDocument.load(inputStream)) {PDFTextStripper stripper = new PDFTextStripper();return stripper.getText(document);}}/*** 將內容按照字段存儲進行匹配* @param content* @return*/public static Map<String,String> setResume(String content,String fileName,String filePath){// map用來存儲解析到的內容Map<String,String> map = new HashMap<>();map.put("file_name",fileName);map.put("file_path",filePath);String skillRegex ="專業技能\\s+(.*?)(?=工作經歷|$)"; ; // "專業技能\r?\n([\s\S]+)"String skill = regex(skillRegex,content);System.err.println("--------------專業技能-------------");System.err.println("skills:"+skill);map.put("skills",skill);String phoneRegex = "聯系方式:(\\d+) 郵箱:(\\S+)";String phone = regex(phoneRegex,content);System.err.println("--------------聯系電話-------------");System.err.println("phone"+phone);map.put("phone",phone);String titleRegex = "求職意向\\s+(.*?)(?=簡介|$)";String title = regex(titleRegex,content);System.err.println("--------------求職意向-------------");System.err.println("title"+title);map.put("title",title);String summaryRegex = "簡介\\s+(.*?)(?=獲獎及證書|$)";String summary = regex(summaryRegex,content);System.err.println("--------------簡介即總結-------------");System.err.println("summary"+summary);map.put("summary",summary);String experienceRegex = "工作經歷\\s+(.*?)(?=工作項目經歷|$)";// "工作項目經歷\\r?\\n([\\s\\S]+)"String experience = regex(experienceRegex,content);System.err.println("--------------工作項目經歷-------------");System.err.println("experience"+experience);map.put("experience",experience);String projectRegex = "工作項目經歷\\s+(.*)";// "工作項目經歷\\r?\\n([\\s\\S]+)"String project = regex(projectRegex,content);System.err.println("--------------工作項目經歷-------------");System.err.println("content"+project);map.put("content",project);String educationRegex = "教育經歷\\s+(.*)"; // "< < < 個人信息\\s*(.*?)(?=< < < 教育背景)"String education = regex(educationRegex,content);System.err.println("--------------教育背景-------------");System.err.println("education"+education);map.put("education",education);String certificationRegex = "獲獎及證書\\s+(.*?)(?=專業技能|$)";String certification = regex(certificationRegex,content);System.err.println("--------------獲獎及證書-------------");System.err.println("certifications"+certification);map.put("certifications",certification);return map;}/*** 匹配規則* @param regex 匹配要求* @param content 需要匹配的內容* @return 匹配結果*/public static String regex(String regex,String content){Pattern pattern=Pattern.compile(regex,Pattern.DOTALL);// 如果想要獲取多行,這里一定添加的是Pattern.DOTALLMatcher matcher=pattern.matcher(content);if(matcher.find()){String data=matcher.group(1).trim();return data;}return null;}
}
代碼
前端
<template><div class="container"><div class="my-myResume"><!--簡歷編輯頁面--><el-form :model="myResume" ref="resumeForm" label-width="120px" class="myResume-form"><el-form-item label="求職意向" prop="title"><el-input v-model="myResume.title" placeholder="請輸入簡歷標題"></el-input></el-form-item><el-form-item label="聯系方式A" prop="summary"><el-input type="textarea" v-model="myResume.phone" placeholder="請輸入您的手機號碼"></el-input></el-form-item><el-form-item label="個人介紹" prop="summary"><el-input type="textarea" v-model="myResume.summary" placeholder="請輸入個人介紹"></el-input></el-form-item><el-form-item label="工作經歷" prop="experience"><el-input type="textarea" v-model="myResume.experience" placeholder="請輸入工作經歷"></el-input></el-form-item><el-form-item label="工作項目經歷" prop="content"><el-input type="textarea" v-model="myResume.content" placeholder="請輸入工作項目經歷"></el-input></el-form-item><el-form-item label="教育經歷" prop="education"><el-input type="textarea" v-model="myResume.education" placeholder="請輸入教育經歷"></el-input></el-form-item><el-form-item label="專業技能" prop="skills"><el-input type="textarea" v-model="myResume.skills" placeholder="請輸入專業技能"></el-input></el-form-item><el-form-item label="獲獎及證書" prop="certifications"><el-input type="textarea" v-model="myResume.certifications" placeholder="請輸入獲得的認證"></el-input></el-form-item><el-button type="primary" @click="handleSubmit">提交</el-button></el-form></div><div class="pdfModule"><!-- 上傳PDF按鈕--><el-button type="primary" @click="handleImport">上傳PDF簡歷</el-button><div v-if="uploadedFileName" class="file-name">已上傳文件:{{ uploadedFileName }}</div><!-- 上傳對話框--><el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body="true"><el-uploadref="upload":limit="1"accept=".pdf":headers="upload.headers":action="upload.url":disabled="upload.isUploading":on-progress="handleFileUploadProgress":on-success="handleFileSuccess":auto-upload="false"><i class="el-icon-upload"></i><div class="el-upload__text">將文件拖到此處,或 <em>點擊上傳</em></div><div class="el-upload__tip text-center" slot="tip"><span>僅允許導入pdf格式文件</span></div></el-upload><div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitFileForm">確定</el-button><el-button @click="upload.open = false">取消</el-button></div></el-dialog></div></div>
</template><script>
import {ElForm, ElFormItem, ElInput, ElButton, ElMessage} from 'element-plus';
import {updateResume, getResumeByUsername, uploadResume, getUserIdByUsername} from '@/api/myResume/myResume'; // 更新API路徑import Cookies from 'js-cookie'import axios from 'axios';import {getToken} from "@/utils/auth.js";export default {name: 'MyResume',data() {return {// 初始化簡歷對象myResume: {resume_id: null, //初始化為null,后續從當前用戶獲取title: '',phone:'',summary: '',experience: '',content:'',education: '',skills: '',certifications: '',file_name:'',file_path:'',},// 簡歷導入參數upload:{open:false,title:"上傳PDF簡歷",isUploading:false,headers:{ Authorization:"Bearer "+getToken()},// url:process.env.VUE_APP_BASE_API+"/resumes/resume/import"url:"http://localhost:8088/student/myResume/parsepdf"},uploadedFileName:'', // 存儲上傳的文件名稱};},methods: {// 導入按鈕操作/*** 打開上傳對話框*/handleImport(){this.upload.title ="上傳PDF簡歷";this.upload.open = true;},/*** 文件上傳中處理*/handleFileUploadProgress(event,file,fileList){this.upload.isUploading = true;console.log("文件上傳中", event, file, fileList);},/*** 文件上傳成功處理*/async handleFileSuccess(response,file){this.upload.open = false;this.upload.isUploading = false;this.$refs.upload.clearFiles();if(response.code===200){this.fillFormWithPDFData(response.data);// 將解析的數據填充到表單中this.uploadedFileName = file.name; //顯示上傳的文件名稱ElMessage.success('文件上傳成功');}else{ElMessage.error('文件解析失敗');}},/*** 提交上傳的文件*/submitFileForm(){console.log("上傳接口 URL:", this.upload.url); // 調試日志this.$refs.upload.submit();},// 將解析的PDF數據填充到表單中fillFormWithPDFData(data) {this.myResume.title = data.title || '';this.myResume.phone = data.phone || '';this.myResume.summary = data.summary || '';this.myResume.experience = data.experience || '';this.myResume.education = data.education || '';this.myResume.skills = data.skills || '';this.myResume.certifications = data.certifications || '';this.myResume.content = data.content || '';this.myResume.file_name = data.file_name || '';this.myResume.file_path = data.file_path || '';},// 提交表單更新簡歷async handleSubmit() {try {const username = this.getCurrentUsername(); // 獲取當前用戶的usernameconsole.log(username);if(!username){this.$message.error('未獲取到用戶信息');return;}const res = await updateResume(this.myResume);// 調用更新簡歷的APIconst userId = await getUserIdByUsername(username);console.log(userId);// const res = await axios.post(url, this.myResume);if (res.code === 200) {ElMessage.success('簡歷更新成功');} else {ElMessage.success('簡歷更新失敗');}} catch (error) {console.error('提交失敗:', error);ElMessage.success('簡歷更新失敗');}},// 獲取簡歷數據 (初始加載)async fetchResumeData() {try {const username = await this.getCurrentUsername();const response = await getResumeByUsername(username); // 調用獲取簡歷數據的方法if (response.code === 200) {this.myResume = response.data; // 使用返回的數據更新 myResumethis.uploadedFileName = this.myResume.file_name;// 顯示已上傳的文件名稱if(this.uploadedFileName){this.upload.open = true;}} else {console.error('獲取簡歷數據失敗:', response.msg);}} catch (error) {console.error('請求失敗:', error);}},// 獲取當前用戶的usernamegetCurrentUsername(){const name = Cookies.get('username');return name;// return this.$store.state.user.userId;// return localStorage.getItem('userId');}},created() {this.fetchResumeData(); // 頁面加載時獲取簡歷數據}};
</script><style scoped>/* 容器布局 */
.container {display: flex;width: 100%;height: 100vh; /* 使容器占滿整個視口高度 */background-color: #f9f9f9; /* 淺灰色背景 */
}/* 簡歷編輯區域 */
.my-myResume {flex: 7; /* 占據 4 份 */padding: 20px;overflow-y: auto; /* 如果內容過多,允許滾動 */
}/* PDF上傳區域 */
.pdfModule {flex: 2; /* 占據 1 份 */padding: 20px;/*border-left: 1px solid #ddd; !* 添加左邊框分隔 *!*/
}/* 表單樣式 */
.myResume-form {max-width: 800px; /* 限制表單最大寬度 */margin: 0 auto; /* 居中顯示 */
}.file-name{margin-top: 10px;font-size: 14px;color:#666;
}.el-upload__text {font-size: 14px;color: #666;
}.el-upload__tip {font-size: 12px;color: #999;
}.dialog-footer {text-align: right;
}
</style>
- js內容
// src/myResume/myResume.jsimport request from '@/utils/request'
// 根據username獲取userId
export function getUserIdByUsername(username){return request({url:`/student/myResume/getUserId/${username}`,method:'get'})
}
// 更新簡歷數據
export function updateResume(data) {return request({url: '/student/myResume/updateResume',method: 'put',data: data})
}// 根據username獲取簡歷數據
export function getResumeByUsername(username) {return request({url: `/student/myResume/getByUsername/${username}`,method: 'get',})
}