当前位置: 首页 > news >正文

springboot图片上传到本地

后端控制器层

业务层

private static final String UPLOAD_DIR = "D:\\p11_项目\\前端\\vue-p11_gq\\src\\assets"; // 上传目录

if (file.isEmpty()) {R.error("照片必须上传!");
}
// 生成唯一文件名
String originalFilename = file.getOriginalFilename();
String extension = StringUtils.getFilenameExtension(originalFilename);
String fileName = UUID.randomUUID().toString() + "." + extension;
// 指定保存路径
Path uploadPath = Paths.get(UPLOAD_DIR);
if (!Files.exists(uploadPath)) {try {Files.createDirectories(uploadPath);} catch (IOException e) {e.printStackTrace();return R.error("创建上传目录失败");}
}
// 保存文件
try {Files.copy(file.getInputStream(), uploadPath.resolve(fileName));
} catch (IOException e) {e.printStackTrace();return R.error("保存图片失败");
}
manageClock1.setPhoto(fileName);

前端展示

<img :src="require(`@/assets/${this.photo}`)" alt="" width="100px" height="100px">

前端添加表单

<el-form-item label="今日帅照" :label-width="formLabelWidth"><input type="file" accept="image/*" @change="onFileChange" ref="fileInput"><img v-if="this.photo" :src="this.photo" alt="预览图片" width="100px" height="100px">
</el-form-item>

前端处理图片方法

Add() {if (!this.form.oneWord || !this.photo) {this.$message.error('请填写完整信息并上传照片');return;}this.form.userId=this.user.id;const formData = new FormData();formData.append('userId',this.form.userId);formData.append('oneWord',this.form.oneWord);formData.append('image', this.$refs.fileInput.files[0]);this.$axios.post(`manage-clock/add`,formData).then(res => {if(res.data.code===200) {this.$message.success("签到成功")this.statu="已签到"this.dialogFormVisible=false;this.show();}else{this.$message.error(res.data.msg)}})
},
onFileChange(event) {const file = event.target.files[0];if (!file) {this.photo = null;return;}const reader = new FileReader();reader.onload = (e) => {this.photo = e.target.result;};reader.readAsDataURL(file);
},


http://www.mrgr.cn/news/52073.html

相关文章:

  • art虚拟机中的gcroot
  • 证明一个特定形式的函数在其三个正根中,两个较小根处的导数之和小于零
  • 北京十大取保候审律师事务所有哪些
  • Linux 命令 chown 和 chmod 的区别
  • 进行SEDEX认证需要准备哪些资料?
  • Java中Dom4j的配置与使用详细解析
  • 为什么k8s不支持docker-kubernetes
  • 【ArcPy】在pycharm中调试arcpy工具代码
  • c语言库文件
  • c++初阶数据结构速成
  • 自动驾驶系统研发系列—智能驾驶新技能:MEB低速紧急制动系统带来更多驾驶安全保障
  • 充电宝哪个品牌性价比高?2024精选五款推荐,新手买前必看!
  • 就是这个样的粗爆,手搓一个计算器:卡路里计算器
  • 产品经理图书推荐 《人工智能产品经理:AI时代PM修炼手册》
  • 基于单片机的搬运机器人控制系统
  • OpenCV高级图形用户界面(15)注册一个回调函数来处理鼠标事件的函数setMouseCallback()的使用
  • Cannot determine local hostname
  • KNN的 k 设置的过大会有什么问题
  • ZBrush和3D-Coat各自的优缺点是什么?
  • 番茄工作法计时器:高效时间管理利器