vue axios上传base64文件数据,后台无法获取获取到数据

1.html标签

accept设置为"image/png,image/gif,image/jpeg",以接受图片文件

<input class="upload-file" @change="handleUpload($event)" type="file" id="imgUploader" accept="image/png,image/gif,image/jpeg">

2.完整代码

axios的post请求需放在onload中,否则后台接受不到base64转化后的数据。

<template>
  <div class="upload-form">
    <div class="upload-block">
      <label class="upload-label">
        <i class="icon icon-plus"></i>
        <img class="upload-img" v-if="upload.src" :src="upload.src" alt="图片">
        <input class="upload-file" @change="handleUpload($event)" type="file" id="imgUploader" accept="image/png,image/gif,image/jpeg">
      </label>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import Toast from 'mint-ui'
import { SUCCESS } from '@/utils/responseStatus'
import Axios from 'axios'
import qs from 'qs'
export default {
  data () {
    return {
      upload: {
        src: '',
        annexId: ''
      },
      annex: {
        FileName: '',
        Extension: '',
        AnnexId: '',
        Base64Str: '',
        Width: 0,
        Height: 0
      }
    }
  },
  methods: {
    handleUpload (e) {
      let that = this
      // 未选择文件,退出
      if (!e.target.files[0]) {
        return
      }
      // 初始化annex
      let file = e.target.files[0]
      // 截取文件名、类型
      let lastIndex = file.name.lastIndexOf('.')
      if (lastIndex !== -1) {
        that.annex.Extension = file.name.substring(lastIndex + 1)
        that.annex.FileName = file.name.substring(0, lastIndex)
      }
      // 转base64
      // 创建一个FileReader
      let reader = new FileReader()
      reader.readAsDataURL(e.target.files[0])
      reader.onload = () => {
        that.upload.src = reader.result
        let idx = reader.result.indexOf(',')
        console.log(reader.result)
        if (idx !== -1) {
          that.annex.Base64Str = reader.result.substring(reader.result.indexOf(',') + 1)
        }
        let img = new Image()
        img.src = reader.result
        img.onload = () => {
          // 文件上传应放在文件读取完成后,否则读取不到base64、width、height
          that.annex.Width = img.width
          that.annex.Height = img.height
          // qs将annex对象转为URI encode字符串
          let params = qs.stringify({ 'annex': that.annex })
          console.log(params)
          Axios.post('/AnnexInfo/UploadAnnex', params, {
            // 设置请求头
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
          }).then(({ data }) => {
            console.log(data)
            if (data.Code === SUCCESS) {
              this.upload.annexId = data.Data
              return
            }
            Toast({
              message: data.Message,
              iconClass: 'icon icon-warning'
            })
          }).catch(err => {
            Toast({
              message: '图片上传失败,原因:' + err,
              iconClass: 'icon icon-warning'
            })
          })
        }
      }
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.upload-form {
  .upload-block {
    padding 5px 0
    display: flex;
    .upload-label {
      position: relative;
      margin: 0 auto;
      width: 100px;
      height: 100px;
      background-color: #f2f2f2;
      border-radius: 8px;
      border: solid 1px #cccccc;
      color: #CCC;
      .icon-plus {
        font-size: 39px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
      }
      .upload-img {
        width: 100%;
        height: 100%;
      }
      .upload-file {
        display: none;
      }
    }
  }
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前置知识: - Vue3.0 - Axios - 微服务 Axios是一个基于Promise的HTTP库,可以用于浏览器和Node.js。在Vue中,我们通常使用Axios发送HTTP请求。 微服务是一种面向服务架构的软件设计风格。它把一个应用划分为一些小的、独立的、可替换的服务,每个服务运行在自己的进程中,服务之间通过轻量级通信机制互相协作。微服务架构可以提高应用的可伸缩性和可维护性。 下面是一个基于Vue3和Axios的微服务请求封装示例: 1. 安装Axios ``` npm install axios ``` 2. 创建axios实例 ```js import axios from 'axios' const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // 微服务请求的基础路径 timeout: 5000 // 超时时间 }) // 请求拦截器 service.interceptors.request.use( config => { // 在请求发送之前做些什么 return config }, error => { // 对请求错误做些什么 console.log(error) // for debug return Promise.reject(error) } ) // 响应拦截器 service.interceptors.response.use( response => { // 对响应数据做些什么 const res = response.data if (res.code !== 20000) { // 如果响应状态码不是20000,则视为错误 return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { // 对响应错误做些什么 console.log('err' + error) // for debug return Promise.reject(error) } ) export default service ``` 3. 封装请求方法 ```js import request from '@/utils/request' export function getUserInfo() { return request({ url: '/user/info', method: 'get' }) } export function login(data) { return request({ url: '/user/login', method: 'post', data }) } export function logout() { return request({ url: '/user/logout', method: 'post' }) } ``` 在组件中使用: ```js import { getUserInfo } from '@/api/user' export default { name: 'HelloWorld', created() { getUserInfo().then(response => { console.log(response) }) } } ``` 这样就完成了基于Vue3和Axios的微服务请求封装。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值