用vue/axios/formdata实现文件上传

责编:menVScode 2019-01-07 22:48 阅读(3190)

构造formData,使用axios上传文件

在项目中使用axios上传文件,记得new一个纯净的axios或者考虑用ajax请求。因为axios在项目估计已经用了全局配置请求头等信息,这里的配置可能被全局请求头拦截,导致请求失败。

1、html部分

<a class="fileBox" href="javascript:;">
    导入商品<input id="fileBtn" ref="fileBtn" name="file" type="file" @change="addExcel"/>
</a>

2、构造formData

let param = new FormData() //创建form对象
param.append('name', 'MVC前端网')//通过append向form对象添加数据
param.append('url', 'menvscode.com')
param.append('token', getToken())
console.log(param.get('file')) //FormData私有类对象,访问不到,可以通过get判断值是否传进去

3、配置全局请求头

let config = {
    headers: {
        'Content-Type': 'multipart/form-data',
        'token': getToken()
    }
}

4、axios发送请求

axios.post('/shop/buy/list', param, config).then((res) => {
    let result = res.data.data
    if (res.data.code === 1000) {
        this.$alert(`共 ${result.failCount + result.successCount} 条数据, 成功 ${result.successCount} 条, 失败 ${result.failCount} 条`, '处理完成', {
            confirmButtonText: '确定',
            callback: action => {}
        })
         return false
    }
    this.$message.error({ message: res.data.msg })
})

5、全部代码

<template>
  <div class="addCoupon">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="" class="btnBox">
        <a class="fileBox" href="javascript:;">
          导入商品<input id="fileBtn" ref="fileBtn" name="file" type="file" @change="addExcel"/>
        </a>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    setAddActivity,
    setSelectActivityGoods,
    addFullActivity,
    addFullGoods,
    editFullActivity,
    updateFullGoods
  } from '@/api/marketing'

  import { getToken } from '@/utils/auth'

  import axios from 'axios'

  export default {
    data() {
      return { }
    },
    methods: {
      addExcel(e){
        let file = e.target.files[0]
        let param = new FormData() //创建form对象
        param.append('discountId', this.id)//通过append向form对象添加数据
        param.append('fileGoodsId', file)//通过append向form对象添加数据
        param.append('token', getToken())
        //console.log(param.get('file')) //FormData私有类对象,访问不到,可以通过get判断值是否传进去

        let config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'token': getToken()
          }
        }

        this.$refs.formRef.validate(valid => {
          if (valid) {
            axios.post('/shop/discount/uploadGoodsIdList', param, config).then((res) => {
              let result = res.data.data
              if (res.data.code === 1000) {
                this.$alert(`共 ${result.failCount + result.successCount} 条数据, 成功 ${result.successCount} 条, 失败 ${result.failCount} 条`, '处理完成', {
                  confirmButtonText: '确定',
                  callback: action => {}
                })
                return false
              }
              this.$message.error({ message: res.data.msg })
            })
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  /deep/ label {
    width: 120px;
  }
  // 美化type=file按钮
  .fileBox{
    position: relative;
    top: 13px;
    left: 10px;
    /*cursor: pointer;*/
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 7px 20px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    input {
      position: absolute;
      font-size: 100px;
      right: 0;
      top: 0;
      opacity: 0;
    }
  }
</style>


发送表单,也是如出一辙,如下

submit(event) {
 let formData = new FormData()
 formData.append('name', this.name)
 formData.append('file', this.file)
 let config = {
   headers: {
      'Content-Type': 'multipart/form-data'
   }
 }
 axios.post('/shop/discount/uploadGoodsIdList', param, config).then((res) => {
     /*这里处理逻辑*/
 })
}
前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码