VUE3 使用原生JS文件上传

211 阅读1分钟
<script lang="ts" setup>

import axios from 'axios'


const addImage = (event) => {
  // 获取选中的文件
  const file = event.target.files[0];

  // 创建一个FormData对象,用于封装文件数据
  const formData = new FormData();
  formData.append('file', file);

  // 使用axios或其他HTTP库发送POST请求,将文件上传到服务器
  axios.post( BASE_FALLBACK_URL_IN(域名) + '/api/Ajax/upload', formData, {
    headers: {
       //头部提交参数
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    if(response.status === 200 && response.data.code === 1){
      editor.value!.chain().focus().setImage({ src: response.data.data.file.url}).run()
    }
    // console.log('图片上传成功', response);
  })
  .catch(error => {
    // console.error('图片上传失败', error);
  });
}

<template>
    //上传按钮样式可以自行更改
    <input type="file" @change="addImage" accept="image/*">
</template>