vue3实现图片上传转base64格式

使用一个<input>元素来上传图片,并使用JavaScript的FileReader API将图片转换为Base64编码。

<template>
  <div class="avatar-upload">
    <label for="avatar-upload-input">
      <img :src="form.formObj.user_pic ? form.formObj.user_pic : '../../../public/default.jpg'" id="avatar-preview" alt="Avatar preview">
      <p style="margin-bottom: 15px;">头像上传</p>
    </label>
    <input type="file" @change="updataAvatar" id="avatar-upload-input" style="display: none;">
</div>
</template>

<script setup>
import { updataAvatarApi, userinfoApi,updataUserInfo } from '../../utils/api'
import { Message } from 'view-ui-plus'
import { onMounted, reactive, ref } from 'vue'
let form = reactive({
  formObj: {
    username: '',
    nickname: '',
    email: '',
    user_pic: '',
    id: ''
  }
})
onMounted(() => {
  getUserInfo()
})
// 头像上传
const updataAvatar = (event) => {
  // 获取文件
  let file = event.target.files[0]
  // 图片base64
  const reader = new FileReader();
  if(file) {
    reader.onload = (e) => {
      // e.target.result 就是转化成base64的图片地址 传给后端
      console.log(e.target.result);
      updataAvatarApi({ avatar: e.target.result }).then(res => {
        if(res.code === 0) {
          Message.success(res.message)
          // 重新获取用户信息
          getUserInfo()
        } else {
          Message.success(res.message)
        }
      })
    };
  }
  // 读取文件
  reader.readAsDataURL(file);
}
// 用户信息
const getUserInfo = () => {
  userinfoApi().then(res => {
    if(res.code === 0) {
      form.formObj = res.data
    } else {
      Message.error(res.message)
    }
  }).catch(err => console.log(err))
}
</script>

<style>
.avatar-upload {
  position: relative;
  width: 400px; /* 设置头像的宽度 */
  min-height: 300px; /* 设置头像的高度 */
  padding: 20px 0;
}
 
#avatar-preview {
  width: 100%;
  height: auto; /* 保持头像的宽高比 */
  display: block;
  width: 50px;
  height: 50px; 
  border-radius: 50%;
  margin-bottom: 15px; 
  border: 1px solid #ccc;
}
 
#avatar-upload-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
  height: 50px;
  opacity: 0; /* 使输入框透明,点击时触发选择文件 */
}
 
/* 可以添加一些装饰和动效,使其更加好看 */
</style>

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个vue上传图片并且通过Java后端将图片换成base64的代码示例: Vue前端部分: ``` <template> <div> <input type="file" @change="onFileChange"> </div> </template> <script> export default { methods: { onFileChange(event) { // 获取文件对象 const file = event.target.files[0] // 创建 FileReader 对象 const reader = new FileReader() // 读取文件 reader.readAsDataURL(file) // 文件读取完成后执行的回调函数 reader.onload = () => { // 获取 base64 编码的图片字符串 const base64Image = reader.result // 发送请求到后端 this.postImage(base64Image) } }, postImage(base64Image) { // 发送 Ajax 请求到后端 // 注意这里的 url 和请求方法要根据实际情况进行修改 axios.post('/api/uploadImage', { base64Image }).then(response => { console.log(response.data) }) } } } </script> ``` Java后端部分: ``` @RequestMapping(value = "/api/uploadImage", method = RequestMethod.POST) @ResponseBody public String uploadImage(@RequestBody Map<String, String> requestMap) { try { // 获取 base64 编码的图片字符串 String base64Image = requestMap.get("base64Image"); // 去掉字符串头部的 "data:image/png;base64," 部分 base64Image = base64Image.substring(base64Image.indexOf(",") + 1); // 解码 base64 编码的图片字符串 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片字节流输出到文件 FileOutputStream imageOutFile = new FileOutputStream("image.jpg"); imageOutFile.write(imageBytes); imageOutFile.close(); // 将图片字节流换成 base64 编码的字符串 String base64ImageString = Base64.getEncoder().encodeToString(imageBytes); return base64ImageString; } catch (IOException e) { e.printStackTrace(); return null; } } ``` 这段代码是一个简单的示例,具体实现还需要根据实际情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值