el-upload转为二进制上传的使用示例

<template>
 <div class="model_box">
  <div class="upload_bin">
   <el-dialog
    width="400px"
    title="上传文件"
    :lock-scroll="true"
    :show-close="true"
    @close="cancel_upload"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="upload_dialogVisible"
   >
    <el-upload
     ref="upload"
     drag
     action="#"
     accept="zip"
     :limit="1"
     :headers="headers"
     :on-remove="remove_bin"
     :on-exceed="handleExceed"
     :on-change="handle_model_change"
     :auto-upload="false"
    >
     <i class="el-icon-upload"></i>
     <div class="el-upload__text"><em>点击选择文件上传</em></div>
     <div class="el-upload__tip" slot="tip">只可上传一个zip文件</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
     <el-button size="small" @click="cancel_upload">取 消</el-button>
     <el-button size="small" type="primary" @click="confirm_upload">上 传</el-button>
    </span>
   </el-dialog>
  </div>
 </div>
</template>

<script>
import { upload_version } from '../utils/api'
export default {
 name: 'Test',
 data() {
  return {
   upload_dialogVisible: false,
   headers: {
    'Content-Type': 'application/octet-stream',
   },
   body: '',
   type_list: ['zip'],
   file_type: '',
  }
 },
 methods: {
  // 取消上传
  cancel_upload() {
   this.upload_dialogVisible = false
   this.body = ''
   this.$refs.upload.clearFiles()
  },
  // 确认上传
  confirm_upload() {
   if (!this.body) return this.$message.warning('请先选择文件...')
   console.log('body', this.body)
   upload_version(this.body, this.headers)
    .then(() => {
     this.cancel_upload()
     return this.$message.success('上传成功...')
    })
    .catch((e) => {
     console.log(e)
    })
  },
  // 超出上传文件数目的提示
  handleExceed() {
   return this.$message.warning('只能上传一个文件...')
  },
  // 移除文件
  remove_bin() {
   this.body = ''
   this.$refs.upload.clearFiles()
  },
  // 文件改变时变化
  handle_model_change(file, fileList) {
   this.file_type = ''
   this.type_list.forEach((item) => {
    if (file.name.includes(item)) {
     this.file_type = item
    }
   })
   if (!this.file_type) {
    this.remove_bin()
    return this.$message.warning('文件类型错误')
   }
   let aBlob = new Blob([file.raw], { type: file_type })
   this.body = aBlob
  },
 },
}
</script>

 ps:第二种转为二进制的方法,一般情况下用上面的就可以

let reader = new FileReader()
   reader.onload = () => {
    let binaryData = reader.result
    this.body = binaryData
   }
   reader.readAsArrayBuffer(file.raw)
posted @ 2022-03-28 20:15  yw3692582  阅读(1838)  评论(0)    收藏  举报