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);
},
