Vue 上传材料(使用input)

最近工作中接到一个需求,需要上传一个文件材料,提交时传给后端。使用的框架是Vue

<template>
  <div>
    <input type="file" @change="inputFileChange"> 
    <button type="primary" size="mini" @click="clicks">上传<button>
  </div>
</template>

以下为逻辑部分(JavaScript的部分)

<script>
import submitfile from "xxxxxx" //要传的后端接口
export default {
  data () {
    return {
      files:''
    }
  },
methods: {
inputFileChange(e){
this.files = e.target.files[0] //当input中选择文件时触发一个事件并让data当中的files拿到所选择的文件
},
click() {
if(!this.files){
console.log('请选择文件')
return
let fd = new FormData()
fd.append('file',this.files)
submitfile(fd).then(res => {
          
        })

}
} 
}
</script>

以上是主要的代码,还可以对input所选择的文件进行筛选,可以设置选择文件的类型。

只能选择Excel文件的代码为如以下:

 <input
        ref="fileInput"
        type="file"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        @change="handleFileUpload"
      >

可以定义input的accept属性限制更多的文件类型

还有分享一个自己踩过的坑:

1.不能将files直接当成给接口传的参数,要用formdata

2.定义接口文件中,要注意post接口的传参类型(要注意是不是data)

posted @ 2019-10-25 15:23  Taxpolat  阅读(2179)  评论(0编辑  收藏  举报