Vue3 通过 axios 获取项目本地图片文件进行上传

<template>
  <input
    type="file"
    ref="imageInput"
    style="display: none"
    @change="uploadImage"
  />
</template>
<script lang="tsx" setup>
import axios from 'axios'
import { ref, defineExpose, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const imageInput = ref<any>(null)

// 1、项目本地实现上传 方法
async function localUplaod() {
  const imageUrl = require('@/assets/wxapp-icon/test.png') // 本地项目的路径
  const file = await getLocalImageAsFile(imageUrl)
  const response = await uploadAPI(file)
}

// 2、模拟点击事件,实现 本地电脑选择让图片上传
function handleClick(e) {
  imageInput.value && imageInput.value.click()
}

// 自定义图片上传
async function uploadImage(event) {
  const files = event.target.files
  if (files.length === 0) {
    ElMessage.error('没有选择文件')
    return
  }
  // 读取第一个文件(假设用户只选择一个文件)
  const file = files[0]
  if (!file.type.match('image/*')) {
    ElMessage.error('请选择一个图片文件')
    return
  }
  // 调用上传API函数
  try {
    const response = await uploadAPI(file)
    console.log('上传成功', response)
    ElMessage.success('上传成功')
    close()
  } catch (error) {
    console.log('error', error)
    ElMessage.error('上传失败')
  }
}

// 获取本地图片
async function getLocalImageAsFile(imagePath) {
  try {
    const response = await axios.get(imagePath, {
      responseType: 'blob' // 指定响应类型为blob
    })
    if (response.status === 200) {
      // 使用 Blob 创建 File 对象
      const file = new File([response.data], 'image.png', { type: 'image/png' })
      return file
    }
  } catch (error) {
    console.error('获取图片文件失败:', error)
    throw error
  }
}

// 上传API
function uploadAPI(dataFile) {
  const file = dataFile
  // 组装成文件格式进行上传
  const formDatas = new FormData()
  formDatas.append('file', file)
  return new Promise((resolve, reject) => {
    axios
      .post<any, any>({
        url: `xxx/xxx/xxx/xxx/xxx/xxx  上传地址`,
        data: formDatas,
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped></style>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清云随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值