vue + elementui +axios 的文件上传功能 和文件下载功能

这个是在项目中遇见的,所以记录下来

不多说。直接上代码。

<template>
  <div>
	  <!--<el-upload drag
	       :limit=limitNum
	       :auto-upload="false"
	       accept=".xlsx"
	       :action="UploadUrl()"
	       :before-upload="beforeUploadFile"
	       :on-change="fileChange"
	       :on-exceed="exceedFile"
	       :on-success="handleSuccess"
	       :on-error="handleError"
	       :file-list="fileList">
	    <i class="el-icon-upload"></i>
	    <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
	    <div class="el-upload__tip" slot="tip">只能上传xlsx文件,且不超过10M</div>
  	</el-upload>-->
    <el-upload
    :http-request="uploadFile"
  class="upload-demo"
  
  :action="UploadUrl()"
  :before-upload="beforeUploadFile"
	:on-change="fileChange"
	:on-exceed="exceedFile"
  :on-preview="handlePreview"
	:on-success="handleSuccess"
	:on-error="handleError"
	:file-list="fileList"
  :limit='limitNum'
  >
  <el-button size="small" type="primary" @click="selectfile">导入合格证数据</el-button>
  
</el-upload>
  <!--<br/>
  <el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
  <el-button size="small">取消</el-button>-->
  </div>
</template>

<script>
  export default {
    data() {
      return {
        limitNum: 1,  // 上传excell时,同时允许上传的最大数
        fileList: [],   // excel文件列表
      }
    },
    methods:{
      // 文件超出个数限制时的钩子
      exceedFile(files, fileList) {
        this.$message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length} 个`);
      },
      // 文件状态改变时的钩子
      fileChange(file, fileList) {
        // console.log(file);
        this.fileList.push(file.raw) ;
        // console.log(this.fileList);
        // this.uploadFile()
      },
      // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
      beforeUploadFile(file) {
        // console.log('before upload');
        // console.log(file);
        let extension = file.name.substring(file.name.lastIndexOf('.')+1);
        let size = file.size / 1024 / 1024;
        if(extension !== 'xlsx') {
          this.$message.warning('只能上传后缀是.xlsx的文件');
        }
        if(size > 10) {
          this.$message.warning('文件大小不得超过10M');
        }
      },
      // 文件上传成功时的钩子
      handleSuccess(res, file, fileList) {
        this.$message.success('文件上传成功');
      },
      // 文件上传失败时的钩子
      handleError(err, file, fileList) {
        this.$message.error('文件上传失败');
      },
      UploadUrl:function(){
       // 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
        return ""
      },
      //上传方法
      uploadFile(){

         let form = new FormData()
          // console.log(this.fileList)
          form.append('uploadFile', this.fileList[0]);//有多少条数据appeng的多少次
          this.$axios.post("/hgzManage/importHgz", form, {headers: {'Content-type': 'multipart/form-data'}}).then(res => {
            console.log(res)
            this.$message({
                type: "success",
                message: "导入成功"
              });
              this.fileList= []
          }).catch(err => {
            console.log(err)
          })
      },
      //选择文件
      selectfile() {
        if (this.fileList.length === 0){
          // this.$message.warning('请上传文件');
        } else {
          // let form = new FormData()
          // console.log(this.fileList)
          // form.append('uploadFile', this.fileList[0]);//有多少条数据appeng的多少次
          // this.$axios.post("/hgzManage/importHgz", form, {headers: {'Content-type': 'multipart/form-data'}}).then(res => {
          //   console.log(res)
          // }).catch(err => {
          //   console.log(err)
          // })
          // this.$axios({
          //   method:"post",
          //   url: "/hgzManage/importHgz",
          //   headers:{
          //     'Content-type': 'multipart/form-data'
          //   },
          //   data:form
          // }).then(
          //   res=>{

          //   },err =>{
          //   });
        }
      },
      handlePreview(file) {
        console.log(file);
      },

    }
  }
</script>

<style scoped>

</style>

注释写的很明确了,只能上传一个文件,如果上传多个需要后端也需要支持上传数组。

现在直接上传的是一个二进制文件。

下载方法

查了很多方法都不行,我用这样的方法解决了,仅供参考

  <el-button size="small" type="primary" ><a :href='"/enterprise/hgzManage/exportTemplate"' style="color:#FFF" > 模板下载</a></el-button>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

new 前端

请博主喝杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值