关于vue+element上传文件post请求

关于vue+element上传文件post请求
由于项目要求这里要实现点击上传文件

在这里插入图片描述
首先,我们需要写个上传组件

  <el-upload
          class="upload-demo"
          :action="doupload()"
          :before-upload="before_Upload"
          ref="newupload"
          :data="data"
           multiple
          :file-list="fileList"
          >
          <el-button style="background-color:#F95714;border-radius:4px;width:220px;height:40px;color:#fff" >上传附件</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
        </el-upload>

利用before-upload属性
  此种方式有个弊端,就是action是必选的参数,那么action如果和post的url一致,总会请求2次,所以一般把action随便写一个url,虽然不影响最终效果,但是这样会在控制台总有404错误报出

  doupload() {
        return api.uploadAnnexInfo/  // 一次接口
      },
    //上传
      before_Upload(file) {
      //  表单提交方式
        let FormDatas = new FormData()
        FormDatas.append('file',file)
        FormDatas.append('bizTable','candidate')  //其他参数
        FormDatas.append('bizId','6')//候选人id<===========!
        console.log(FormDatas)
          let that = this
          that.$http({
            method:'post',
            url:api.uploadAnnexInfo,   //  二次接口
            headers:headers('multipart/form-data'),
            data:FormDatas
          }).then(function(res){
           if(res.data.code==10000){
              that.$message.success(res.data.msg);
            }else{
              that.$message.error(res.data.msg);
            }
          })
      },      

二、常用方法介绍
1、动态改变action地址
action是一个必填参数,且其类型为string,我们把action写成:action,然后后面跟着一个方法名,调用方法,返回你想要的地址,实现动态的去修改上传地址

//html 代码
<el-upload
 :action="UploadUrl()" 
  :on-success="UploadSuccess"
   :file-list="fileList">
  <el-button size="small" type="primary" >点击上传</el-button>
</el-upload>

// js 代码在 methods中写入需要调用的方法
methods:{
    UploadUrl:function(){
        return "返回需要上传的地址";     
    }   
}

2、在文件上传前做类型大小等限制
(1)一种方式是,加accpet属性

<el-upload class="upload-demo" 
:multiple="true"
 :action="action"
  accept="image/jpeg,image/gif,image/png,image/bmp" 
:file-list="fileList"
 :before-upload="beforeAvatarUpload"
 :on-success="handleAvatarSuccess">

(2)另一种方式是在上传前的触发函数里面去判断

beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isGIF = file.type === 'image/gif';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip('上传图片必须是JPG/GIF/PNG/BMP 格式!');
    }
    if (!isLt2M) {
        this.common.errorTip('上传图片大小不能超过 2MB!');
    }
    return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
},

3、同时传递form表单及有多个upload文件该如何传递?

newSubmitForm () {
  this.$refs['newform'].validate((valid) => {
    if (valid) {
      //表单的数据
      this.uploadForm.append('expName', this.newform.expName)
      this.uploadForm.append('expSn', this.newform.expSn)
      this.uploadForm.append('groupId', this.newgroupId)
      this.uploadForm.append('subGroupId', this.newsubgroupId)
      this.uploadForm.append('expvmDifficulty', this.newform.expvmDifficulty)
      
      newExp(this.uploadForm).then(res => {
        if (res.code === 400) {
          this.$message.error(res.error)
        } else if (res.code === 200) {
          this.$message.success('上传成功!')
        
        }
      })
      this.$refs.uploadhtml.submit()   // 提交时分别触发各上传组件的before-upload函数
      this.$refs.uploadfile.submit()
      this.$refs.uploadvideo.submit()   
    } else {
      console.log('error submit!!')
      return false
    }
  })
},
newHtml (file) {   // before-upload
  this.uploadForm.append('html', file)
  return false
},
newFiles (file) {
  this.uploadForm.append('file[]', file)
  return false
},
newVideo (file) {
  this.uploadForm.append('video', file)
  return false
}
export function newExp (data) {
  return axios({
    method: 'post',  // 方式一定是post
    url: '你的后台接收函数路径',
    timeout: 20000,
    data: data        // 参数需要是单一的formData形式
  })
}

注意:(1)对于多个上传组件来说,需要分别触发,去给FormData append数据
   (2)接收多文件一定要是数组形式的file[],this.uploadForm.append(‘file[]’, file)
  
4、如何传递文件和其他参数
  就像第一节那样,如果不使用action实现上传,而使用before-upload属性也能实现上传的效果。
  before-upload属性,这是一个function类型的属性,默认参数是当前文件,只要能传递这个文件也能实现效果
  要传递这个方法就需要new一个formdata对象,然后对这个对象追加key和value,类似于postman测试时那样。
  另外注意:传递formdata和data不能一起传递,要传递formdata就不能有data,所以对于其他参数的传递,也要改为

beforeUpload (file,id) {
    let fd = new FormData()
    fd.append('file', file)
    fd.append('id',id)//其他参数
    axios.post(url, fd, {
    })
 },

而不能使用这种又有FormData,又有data的模式

beforeUpload (file,id) {
        let fd = new FormData()
        fd.append('key', file, fileName)
        axios.post(url, fd,{
          data:{
           id:id
          },
          headers: {
           'Content-Type': 'multipart/form-data'
          }
        })
     },
  • 8
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,这是一个比较复杂的问题,我将尽可能详细地回答你。 首先,你需要在 Vue 项目中安装 Vuex、Vue Router、Element UI 和 Axios 这些库。可以通过以下命令来安装它们: ``` npm install vuex vue-router element-ui axios --save ``` 接下来,你需要创建一个 Vuex 的 store 来存储应用程序的状态。在 store 中,你可以定义一些 mutation、action 和 getter 来改变状态。 在这个示例中,我们需要定义一个 state 来存储我们的数据,例如: ```javascript const state = { items: [], currentItem: {} } ``` 然后,我们需要定义一些 mutation 来改变 state 中的数据。例如: ```javascript const mutations = { setItems(state, items) { state.items = items }, setCurrentItem(state, item) { state.currentItem = item } } ``` 接下来,我们需要定义一些 action 来处理异步请求。例如: ```javascript const actions = { fetchItems({ commit }) { axios.get('/api/items.json').then(response => { commit('setItems', response.data) }) }, addItem({ commit, state }, item) { axios.post('/api/items.json', item).then(response => { commit('setItems', [...state.items, response.data]) }) }, updateItem({ commit, state }, item) { axios.put('/api/items/' + item.id + '.json', item).then(response => { const index = state.items.findIndex(i => i.id === response.data.id) const items = [...state.items] items[index] = response.data commit('setItems', items) commit('setCurrentItem', {}) }) }, deleteItem({ commit, state }, id) { axios.delete('/api/items/' + id + '.json').then(response => { const items = state.items.filter(i => i.id !== id) commit('setItems', items) }) } } ``` 这些 action 将发送请求到我们的 API 并更新 store 中的数据。例如: - `fetchItems` 将获取所有数据并将其设置到 `items` 中。 - `addItem` 将添加一个新的数据项并将其添加到 `items` 中。 - `updateItem` 将更新一个数据项并将其更新到 `items` 中。 - `deleteItem` 将删除一个数据项并将其从 `items` 中删除。 最后,我们需要定义一些 getter 来获取我们的数据。例如: ```javascript const getters = { allItems: state => state.items, currentItem: state => state.currentItem } ``` 现在,我们已经完成了 store 的设置。接下来,我们需要创建一个 Vue 组件来渲染我们的数据,例如: ```html <template> <div> <el-table :data="items" style="width: 100%"> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> <el-table-column prop="address" label="Address"></el-table-column> <el-table-column> <template slot-scope="{ row }"> <el-button @click="editItem(row)">Edit</el-button> <el-button @click="deleteItem(row.id)">Delete</el-button> </template> </el-table-column> </el-table> <el-dialog :visible.sync="dialogVisible"> <el-form :model="currentItem" label-position="left" ref="form"> <el-form-item label="Name"> <el-input v-model="currentItem.name"></el-input> </el-form-item> <el-form-item label="Age"> <el-input-number v-model="currentItem.age"></el-input-number> </el-form-item> <el-form-item label="Address"> <el-input v-model="currentItem.address"></el-input> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">Cancel</el-button> <el-button type="primary" @click="submitForm">Save</el-button> </div> </el-dialog> <el-button @click="addItem()">Add Item</el-button> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { computed: { ...mapState(['items', 'currentItem']) }, methods: { ...mapActions(['fetchItems', 'addItem', 'updateItem', 'deleteItem']), editItem(item) { this.$store.commit('setCurrentItem', item) this.dialogVisible = true }, deleteItem(id) { this.deleteItem(id) }, submitForm() { const form = this.$refs.form form.validate(valid => { if (valid) { if (this.currentItem.id) { this.updateItem(this.currentItem) } else { this.addItem(this.currentItem) } this.dialogVisible = false } }) } } } </script> ``` 在这个组件中,我们使用 Element UI 的表格和表单来渲染我们的数据。我们还使用了 Vuex 的 mapState、mapActions 来将 store 中的状态和操作映射到组件的计算属性和方法中。 现在,我们已经完成了一个基于 VueVuex、Vue Router、Element UI 和 Axios 的增删改查应用程序。当然,这个示例并不是完美的,你可能需要根据你的具体需求做一些适当的调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值