大文件切片上传


<template>
    <div>
      <!-- 图片类型上传 -->
      <b-modal ref="uploadingImg" scrollable centered static no-close-on-backdrop
               :title="$t('上传图片')"
               :hide-footer="true"
               :dialog-class="'default'"
               :header-class="['modal_header','justify-content-between','align-items-center']"
               :header-bg-variant="headerBgVariant"
               :header-text-variant="headerTextVariant">
        <div>
          <b-input-group size="sm" :prepend="$t('顶部深度')" class="mb-2" v-if="!this.isDeep">
            <b-form-input v-model="pictureData.minDepth" type="number"></b-form-input>
          </b-input-group>
          <b-input-group size="sm" :prepend="$t('底部深度')" class="mb-2" v-if="!this.isDeep">
            <b-form-input v-model="pictureData.maxDepth" type="number"></b-form-input>
          </b-input-group>
          <b-input-group size="sm" :prepend="$t('取样深度')" class="mb-2" v-if="this.isDeep">
            <b-form-input v-model="pictureData.minDepth" type="number"></b-form-input>
          </b-input-group>
          <b-input-group size="sm" prepend="数据空间" class="mb-2" v-if="this.space">
            <span style="margin:0 10px">X:</span><b-form-input v-model="pictureData.spaceX" type="number"></b-form-input>
            <span style="margin:0 10px">Y:</span><b-form-input v-model="pictureData.spaceY" type="number"></b-form-input>
            <span style="margin:0 10px">Z:</span><b-form-input v-model="pictureData.spaceZ" type="number"></b-form-input>
          </b-input-group>
          <b-input-group size="sm" :prepend="$t('图片类型')" class="mb-2">
            <b-form-select size="sm" @change="pictureTypeChange" v-model="pictureData.pictureTypeName">
              <option value="PNG" >PNG</option>
              <option value="JPG" >JPG</option>
              <option value="RAW" >RAW</option>
              <option value="TIF" >TIF</option>
              <option value="BMP" >BMP</option>
            </b-form-select>
          </b-input-group>
        
          <b-input-group size="sm" :prepend="$t('图片文件')" class="mb-2" id="rawFileUp">
            <!-- 图片上传 -->
            <div v-if="!this.BigFile" style="display: flex;align-items: center;">
              <el-upload
                class="upload-demo"
                ref="upload"
                name='files'
                :action='fileUp'
                accept=".jpg,.jpeg,.png"
                :before-upload="onBeforeUpload"
                :on-success="fileSuccess"
                :file-list="fileList"
                :auto-upload="true">
                <el-button slot="trigger" size="small" type="primary">图片上传</el-button>
                <span slot="tip" class="el-upload__tip" style="margin-left:10px">只能上传图片</span>
              </el-upload>
            </div>
            <!-- raw文件上传 -->
            <div v-if="this.BigFile" class="row">
              <el-upload :show-file-list="true" accept="" ref="uploads" :limit="1" action class="mirror-upload" :http-request="putinMirror" :auto-upload="false" >
                <el-button type="primary" :disabled="bigFileBtn">选择文件</el-button> 
              </el-upload>
              <el-button type="primary" @click="commitFile" style="position:absolute;left:180px;" :disabled="OkbigFileBtn">确定上传</el-button> 
            </div>
          </b-input-group>
          <!-- <div v-for="(item,index) in fileNmae"><i class="el-icon-document"></i>{{item}}</div> -->
          <el-progress  :stroke-width='strokeWidth' :percentage="scheduleAll" style="margin:10px 0"></el-progress> 
          <button type="submit" class="btn btn-primary btn-block" @click="toSubmitPictureUrl" v-if="!this.space">{{ $t("提交") }}</button>
          </div>
      </b-modal>

       <!-- 文件上传表头定义弹框 -->
       <UpFile v-if="fileUpValue" :info="upFileInfo" @fileTitle = 'childFun'/>
    </div>
  </template>
  
  <script>
  import {drag} from '@/directive/drag';
  import {helpers, required} from 'vuelidate/lib/validators';
  import ThreeD from '@/components/ThreeD';
  import html2canvas from 'html2canvas';
  import axios from 'axios';
  import {API_URL} from '../common/constants';
  import {getToken} from '../store/modules/user';
  import UpFile from './UpFile'
  import qs from 'qs'
  
  const mobile = helpers.regex('mobile', /^1[3456789][0-9]{9}$/);
  
  export default {
    name: "RightClickMenu",
    components: {
      ThreeD,
      UpFile
    },
   
    data() {
      return {
        strokeWidth:6, // 进度条宽度
        bigFileBtn:false, // raw文件上传选择文件按钮状态
        OkbigFileBtn:false, // raw文件上传提交文件按钮状态
        space:false, // 上传是否显示XYZ
        fileNmae:[], // 上传文件名
        scheduleAll:0, // 文件总数
        pictureData: {
            wellId: '',
            minDepth: '',
            maxDepth: '',
            pictureName: '',
            pictureUrl: '',
            pictureType: 1,
            pictureSubType: 1,
            dnaFileId:'',
            pictureTypeName:'',
            spaceX:'',
            spaceY:'',
            spaceZ:'',
        },
        fileUp:"",
        fileList:[]
      };
    },
    validations: {
      form_pf: {
        organization: {required},
        name: {required},
        sampleCount: {required},
        mobile: {required, mobile},
      }
    },
    methods: {
      // 大文件上传文件类型选择
      pictureTypeChange(info){
        console.log(this.wrapType)
        this.pictureData.pictureTypeName = info
        if(info == 'RAW'){
          this.BigFile=true  
          this.space = true
        }else{
          
          this.isBigFile = true
          this.BigFile=false
          this.space = false
        }
        if(info == 'RAW' && this.wrapType !== 'CT'){
          this.isDeep = true
        }else{
          this.isDeep = false
        }
        console.log(info,11111)
      },

      // 大文件上传确定
      commitFile(){
        this.bigFileBtn = true
        this.OkbigFileBtn = true
        this.$refs.uploads.submit();
      },
      putinMirror(file){
        console.log(file)
        // 每个文件切片大小定为5MB
        var sliceSize = 50 * 1024 * 1024;
        //文件大小限制为最大1个G,可根据需求修改
        var filesizes  = 100 * 1024 * 1024 * 1024;
        let that = this;
        const blob = file.file;
        const fileSize = blob.size;// 文件大小
        this.fileNmae.push(blob.name)
        const fileName = blob.name;// 文件名
        //计算文件切片总数
        var totalSlice = Math.ceil(fileSize / sliceSize);
  
        var num = 0 
        var guid = Date.parse(new Date())
        if(fileSize <= filesizes){
          that.showbtn = false;
          // 循环上传
          for (let i = 0; i < totalSlice; i++) {
              let start = i * sliceSize;
              let chunk = blob.slice(start, Math.min(fileSize, start + sliceSize));
              let files = new File([chunk], fileName)
              var formData = new FormData();   
              formData.append("file", files);
              formData.append("fileName", fileName);
              formData.append("chunks", totalSlice);
              formData.append("guid", guid);
              formData.append("chunk", i);            
              let instance= axios.create({
                baseURL: 'baseUrl',
                data: formData,        
                headers: { 'Content-Type': 'multipart/form-data'}
  
              })
              var num = 0 
              instance.post(`${API_URL}base/fragmentUpload`,formData)
              .then((res)=>{
                num = num +1
                this.scheduleAll = (num/totalSlice*100).toFixed(2)
                if(num == totalSlice){
                axios({
                  method: 'get',
                  url: API_URL + `/base/merge/${guid}?resourceType=3`,
                  headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    'token': getToken(),
                  },
                }).then((res)=>{
                  console.log(res,111111111)
                  if(res.data.code ==0){
                    this.imgFromType = 1
                    this.pictureData.dnaFileId = res.data.dnaFileIdList[0]
                    this.toSubmitPictureUrl()
                  }
                }).catch(()=>{
                        this.$message({
                        message: "解析文件事件较长,请在5分钟后刷新页面查看解析结果!",
                        type: "warning",
                    });
                })
              }
              
              })
              
          }
          
         
        }else{
          that.$message({
            message: '文件大小超出10G',
            type: 'error'
          });
        }
      },
  
   
      
      // 文件上传前
      onBeforeUpload(file){
        if(this.isBigFile){
          // 纳米 微米 全值岩心
          const is100M = file.size / 1024 / 1024 < 100;
          if (is100M) { 
            this.fileAccept = '.txt,.xlsx'
            // 小于100mb文件(纳米 微米 全值岩心)
            
          }else{
            this.fileAccept = '.txt,.xlsx,.raw'
            // 大于100mb文件(纳米 微米 全值岩心)
          }
        }
        else{
          // 其他文件
          this.autoUpload = true
          this.fileAccept = '.txt,.xlsx'
          const is100M = file.size / 1024 / 1024 < 100;
          if (!is100M) {
            this.$message.error("上传图片大小不能超过 100MB!");
            return false
          }
        }
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
        if(this.wrapType == 'CT' || this.wrapType == 'YX' || this.wrapType == 'WM' || this.wrapType == 'NM' ){
          if(this.isEdit == 1){
            if (testmsg == "xlsx" || testmsg =="txt" || testmsg =="raw") { 
              this.autoUpload = true
            }else{
              this.$message({
                message: "上传文件只能是.xlsx格式或者txt!",
                type: "warning",
              });
              return false
            }
          }else if(this.isEdit == 2){
            if (testmsg == "jpg" || testmsg =="jpeg" || testmsg =="png") { 
              this.fileList.push(file)
            }else{
              this.$message({
                message: "上传文件只能是.jpg、.jpeg、.png!",
                type: "warning",
              });
              return false
            }
          } 
        }else{
          if(this.isEdit == 1){
              // this.fileUp = API_URL+`/dna/resource/v2/importResource?resourceType=9&headRows=0&getRows=5`
            if (testmsg == "xlsx" || testmsg =="txt" || testmsg =="raw") { 
              this.autoUpload = true
            }else{
              this.$message({
                message: "上传文件只能是.xlsx格式或者txt!",
                type: "warning",
              });
              return false
            }
          }else if(this.isEdit == 2)
            if (testmsg == "jpg" || testmsg =="jpeg" || testmsg =="png") { 
              this.fileList.push(file)
            }else{
              this.$message({
                message: "上传文件只能是.jpg、.jpeg、.png!",
                type: "warning",
              });
              return false
            }
        }
       
       
  
      },
      // 本地井资源上传
      // 小文件上传成功
      fileSuccess(response){  
        this.$refs.local_well.hide();
        if(response.code ===0 ){
          if(this.isEchoList){
            this.fileUpValue = true // 文件回显
          }
          this.pictureData.dnaFileId = response.dnaFileIdList[0]
          this.dnaFileIdList = response.dnaFileIdList
          this.upFileInfo.tit = this.fileTitle
          this.upFileInfo.value = response.dataLine
          this.upFileInfo.dialogTableVisible = true
        } 
      },
        // 上传文件方法回调
      async childFun(val){ 
        let obj={}
        if(val.list){
          val.list.map((res)=>{
            obj[res.test] = res.name
          })
          if(val.invalid.indexOf(',')){
            this.errorValue = val.invalid.split(',')
          }else{
            this.errorValue.push(val.invalid)
          }
          axios({
              method: 'post',
              url: API_URL + 'dna/resource/parseWellTxt',
              data: {
                dnaFileIdList:this.dnaFileIdList, // 文件id列表
                headerMap:obj, // 表头配置
                overrideFlag:true, // 是否覆盖
                resourceType:this.resourceType, // 文件类型
                headRows:val.num, // 数据起始行数
                errorList:this.errorValue, // 数据无效值
              },
              headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'token': getToken(),
              },
            })
                .then((res) => {
                  if (res.data.code === 0) {
                    console.log(this.lineFileType,2222222222222)
                      this.$emit('takeSet', [this.lineFileType],'')
                    this.fileUpValue = false
                  } else {
                    this.$swal({
                      type: 'error',
                      title: res.data.msg,
                    });
                  }
                })
        }else{
          this.fileUpValue = false
        }
       
               
        
      },
     
  };
  </script>

  

你可能感兴趣的:(javascript,前端,开发语言)