前端文件下載(html5+vue/excel下載)


excel等文件的上傳和下載

一、下載

1.data數據

data () {
    return {
      list:[{name: 'cs1', id: '5'}, {name: 'cs1', id: '24'}],
      selectModule: '', // 選擇某列表中一個
      selectModuleName: '', // 下載的名稱
      selectModuleUrl: '' // 下載的地址
    }
}

2.Dom操作

<div>
  <span>下載模版:</span>
  <el-select v-model="selectModule" @change="handleSelectModule" placeholder="請選擇下載模板" style="margin-left: 20px; width: 300px; height: 36px;">
    <el-option v-for="item in list" :key="item.id" :value="item.id" :label="item.name" />
  </el-select>
  <a :href="selectModuleUrl" :download="selectModuleName">下載</a>
</div>

3.下載

handleSelectModule (val) {
  // 獲取模版下載地址
  const params = {
    fileId: val,
    type: 1
  }
  downLoadExcel(params, '下載地址').then(res => {
    var reader = new FileReader()
    reader.readAsText(res.data, 'gbk')
    const _this = this
    reader.onload = function (e) {
      try {
        var result = JSON.parse(reader.result)
        console.log(result)
        _this.$message({
          type: 'error',
          message: '下載模版不存在'
        })
      } catch (err) {
        const url = window.URL.createObjectURL(res.data)
        let proName = ''
        for (let i = 0; i < _this.list.length; i++) {
          if (_this.list[i].proID === val) {
            proName = _this.list[i].proName
            break
          }
        }
        _this.selectModuleUrl = url
        _this.selectModuleName = `${proName}下載模版名稱.xls`
      }
    }
  }).catch(error => {
    console.log(error)
  })
},

// 下載方法
import axios from 'axios'

function downLoadExcel (params, url) {
  console.log(params, url)
  return axios({
    baseURL: `${API_ROOT}`, // 下載的基本地址, url是拼接下載地址(后綴), 如 http://www.baidu.com/downUrl
    withCredentials: true,
    crossDomain: true,
    url: url,
    method: 'post',
    responseType: 'blob',
    params: params
  })
}

二、上傳

1.data數據data () {    return {

 size: null, // 文件大小  fileInfo: { name: '', file: undefined }, id: '' dialogVisible: false,
    }
}

2.操作dom

   <input ref="fileUpload" type="file" @change="fileUpload($event)" style="width: 0px; height: 0px;visibility: hidden;"/>
    <span v-if="!(fileInfo.name)" @click="handleCheckFile" class="opItem">請選擇上傳類型</span>
    <span class="opItem">{{fileInfo.name}}</span>
    <div class="dialog-content">
     <el-select filterable v-model="selectProject" @change="handleSelectModule" placeholder="請選擇上傳項目" style="margin-left: 20px; width: 300px; height: 36px;">
      <el-option v-for="item in list" :key="item.id" :value="item.id" :label="item.name" />
    </el-select>

3.方法實現

  handleSelectModule () {
    // 調用下載方法
    如上
  }
  handleCheckFile () {
    this.$refs.fileUpload.click()
  },
  fileUpload (e) {
    // console.log(e.target.files[0])
    // let type = e.target.files[0].name.split('.')[1]
    this.fileInfo.name = e.target.files[0].name
    this.fileInfo.file = e.target.files[0]
    this.size = e.target.files[0].size
    // this.size = bigSize / 1024;
    this.$refs.fileUpload.value = null
  },
  uploadList () {
      if (this.size > 30 * 1024 * 1024) {
        this.$message({
          type: 'error',
          message: '文件不能超過30M'
        })
        return
      }
      this.dialogVisible = false
      uploadFileAsync({ file: this.fileInfo.file, id: this.id, url: '/xxxx/uploadExcel' })
        .then(res => {
         console.log('---成功操作')
        })
        .catch(error => {
          this.fileInfo = {
            name: '',
            file: undefined
          }
          this.$message({
            type: 'error',
            message: error.responseMsg
          })
        })
    },
  function uploadFileAsync (params) {
  const { file, id, url } = params
  var formData = new FormData()
  formData.append('uploadFile', file)
  return axios({
    baseURL: `${API_ROOT}`,
    url: url,
    data: formData,
    timeout: 600000,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    withCredentials: true,
    crossDomain: true,
    params: {
      id: id
    }
  }).then(res => {
    return Promise.resolve(res.data)
  }).catch(error => {
    console.log(error)
    return Promise.reject(new Error({ responseCode: '20089', responseMsg: '請求出錯了,請稍后再試' }))
  })

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM