SpringBoot+Vue3 将图片存储到MySQL的一些理解 Base64转码

前期准备

确定好MySQL图片类型的定义,图片要选择mediumblob

之后前端上传图片到后端过去

 

前端页面设计可以参考Overview 组件总览 | Element Plus (element-plus.org)

前端

上传图片

<!-- 上传图片 on-change是用来监视是否有上传文件 有变化就调用相关的方法 -->
                <el-upload limit=1 action="#" :on-change="handleFileChange" list-type="picture-card" :auto-upload="false">

                  <el-icon><Plus /></el-icon>

                  <template #file="{ file }">
                    <div>
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                      <!-- <span class="el-upload-list__item-actions">
                        <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                        </span>
                        <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                      >
                          <el-icon><Download /></el-icon>
                        </span>
                        <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                    <el-icon><Delete /></el-icon>
                        </span>
                      </span> -->
                    </div>
                  </template>
                </el-upload>

当上传图片过后调用的方法

//用于将图片格式转为base64格式编码,用于存储到数据库当中
const handleFileChange = (file) => {
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        // 只取Base64部分 在转的过程中会有MIME类型的格式一起存进来 会有违规字符 所以要去掉
        const base64Data = reader.result.split(',')[1];
        updateform.value.img = base64Data;
        form.value.img = base64Data;
      };
      console.log(updateform.value.img);
    };

之后是调用方法,这里将添加按钮绑定confirm方法

confirm方法

// 提交时增加课程
const confirm = async () => {
      try {
        console.log(form.value);
        //request封装起来了,这里就不提供代码了
        //它的作用就是前后端联调 可以使用axios接口的post方法 实现效果是一样的
        const addcourse = await request.post('/admin/addGood', form.value);
        console.log(addcourse.data);
        successMessage.value = '商品添加成功';
        ElMessage.success(successMessage.value);
        errorMessage.value = '';
        dialogFormVisible.value = false;//关闭对话款
        fetchCourses();//刷新课程列表
        // form.value = null;
      } catch (error) {
        errorMessage.value = error.response.data.message || '添加商品失败,请重试';
        ElMessage.error(errorMessage.value);
        successMessage.value = '';
      }
    };

定义form对象

const form = ref({
  title:'',
  desc:'',
  time:'',
  price:null,
  img:null,
  name:'',
})

后端实现过程

映射方法定义

//增加课程
@PostMapping("/addGood")//HTTP请求中的Post请求用于将数据提交到指定资源进行处理。
public Result addGood(@RequestBody Good good){
    List<Good> existingGood = adminMapper.selectGood(good.getName(),good.getTitle()); //查询新加课程是否已经存在
    int size = existingGood.size();//数组的大小
    if (size != 0){
        //  size为0则存在相同课程,返回课程已存在
        System.out.println(2);
        return Result.error("课程已存在");
    }else{  //不存在就添加入数据库
        System.out.println(1);
        int newgood = adminMapper.addGood(good);
        return Result.success(newgood);
    }
}

在前端你使用的是post方法,“const addcourse = await request.post('/admin/addGood', form.value);” 那么后端需要使用关联的映射PostMapping

SQL语句实现增加课程功能

//增加课程
@Insert("insert into `home_good`(title,`desc`,time,price,img,name,num) " +
        "values (#{title},#{desc},#{time},#{price},#{img},#{name},#{num})")
int addGood(Good good);

你的点赞加关注是我更新的动力哦(⊙o⊙)

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
图片存储到数据库并不是一个好的做法,因为数据库存储的是结构化数据,而图片是二进制数据,会占用大量的数据库存储空间,降低数据库的性能。更好的做法是将图片存储到文件系统或者对象存储中,然后在数据库中存储图片的路径或者文件名。 下面是一个简单的上传图片并将图片路径存储到数据库的示例: 1.前端页面使用Vue上传图片 ```html <template> <div> <input type="file" @change="handleFileChange"> <button @click="uploadImage">上传图片</button> </div> </template> <script> export default { data() { return { file: null } }, methods: { handleFileChange(e) { this.file = e.target.files[0]; }, uploadImage() { let formData = new FormData(); formData.append('file', this.file); axios.post('http://localhost:8080/upload', formData) .then(response => { // 上传成功后,将图片路径存储到数据库 let imagePath = response.data.imagePath; // ... }) .catch(error => { console.log(error); }); } } } </script> ``` 2.后端使用Spring Boot接收并处理上传的图片 ```java @RestController public class UploadController { @Autowired private ImageService imageService; @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { try { // 保存图片到文件系统或者对象存储 String imagePath = imageService.saveImage(file); // 将图片路径存储到数据库 // ... return ResponseEntity.ok().body(new UploadResponse(imagePath)); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } public class UploadResponse { private String imagePath; // getter and setter } @Service public class ImageService { public String saveImage(MultipartFile file) throws IOException { // 保存图片到文件系统或者对象存储 // ... return imagePath; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值