文件上传、下载、在线预览、删除

12 篇文章 1 订阅
 	<el-dialog
        title="上传文件"
        :visible.sync="upload_flag"
        custom-class='dialogClass'
        width="30%">
        <div>
          <el-cascader
            v-model="filePath"
            style="width: 200px"
            :options="pathData"
            :props="{children:'children',label:'name',value:'id',expandTrigger: 'hover', }"
            clearable
            ref="checkedRef"
            placeholder="请选择上传路径"
          ></el-cascader>
        </div>
        <div>
          <el-upload
            :limit=limitNum
            :auto-upload="false"
            :multiple="true"
            action='http://192.168.1.107:9000/pm-projectManage/file/uploadFileInfo'
            style='display: inline-block;margin-left: 10px;height: 200px;'
            accept=".txt,.xlsx,.xls,.jpg,.jpeg,.png,.doc,.docx,.pdf"
            :show-file-list='true'
            :action="UploadUrl()"
            @before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-remove='removeFile'
            :file-list="fileList">
            <el-button size="small" type="primary" style='width: 100px;height: 40px;margin-top: 20px;'>选择文件</el-button>
          </el-upload>
        </div>
        <el-button size="small" type="success" @click="uploadFile" v-prevent-re-click style='width: 100px;height: 40px;position: absolute;right: -25px;bottom: 20px;transform: translateX(-50%)'>确认上传</el-button>
      </el-dialog>
       <!--查看凭据抽屉-->
    <div>
      <el-drawer
        title="查看凭据"
        :visible.sync="lookCredentialVisible"
        :before-close="lookCredentialClose"
      >
        <ul class="ul">
          <li v-for='(item,index) in filesData' :key='index' :name='index'>
            <div>
              <i :class='item.name ? "el-icon-folder" : "el-icon-document"' style='font-size: 25px;margin-left: 10px; color: #6FCEFB;'></i>
              <span style='margin-left: 10px;font-size: 16px;'>{{ item.name ? item.name : item.fileName }}</span>
            </div>
            <div>
              <el-button type='danger' @click='deleteFile(item)' size="small">删除文件</el-button>
              <el-button type='warning' @click='lookFileBtn(item)' size="small">查看文件</el-button>
              <el-button type='success' v-if='!!item.fileName' @click='downLoadBtn(item)' size="small">下载文件</el-button>
            </div>
          </li>
        </ul>
      </el-drawer>
    </div>
    <!--  pdf文件预览对话框  -->
    <div>
      <el-drawer
        title="文件预览"
        :visible.sync="lookVisible"
        style='text-align: center;'
        :direction="direction">
        <pdf
          :src='src'
          class='scroll'
          style='width: 100%;'
          :page='currentPage'
          @page-loaded="currentPage=$event"
          @loaded="loadPdfHandler"
          @progress="loadedRatio = $event"
          @num-pages="pageCount=$event"
        ></pdf>
        <div>
          <el-button-group>
            <el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
            <el-button size="mini" type="text" style="margin-left: 5px;margin-right: 5px;">{{ currentPage }} / {{ pageCount }}</el-button>
            <el-button type="primary" size="mini" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
          </el-button-group>
        </div>
      </el-drawer>
    </div>
  data(){
    return{
      //文件上传部分
      limitNum:10,
      fileList:[],
      addFilesId:'',
      updateFilesId:'',
      upload_flag:false,
      filePath:"",
      pathData:[],
      lookCredentialVisible:false,//查看凭据
      filesData:[],//凭据表
      src:'',//pdf文件预览地址
      lookVisible:false,
      currentPage:1,//pdf页码
      pageCount: 1, // pdf页面总页数
      loadedRatio: 0,//当前页面的加载进度,范围是0-1 ,等于1的时候代表当前页已经完全加载完成了
      direction: 'ltr', // 抽屉从右往左打开
      zIndex: 0,//图片预览
    }
  },

上传文件

	UploadUrl:function(){
      // 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
      return ""
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
    beforeUploadFile(file) {
      console.log('098989')
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      let size = file.size / 1024 / 1024;
      console.log(size)
      if (extension !== 'doc' || extension !== 'docx' || extension !== 'pdf') {
        this.$message.warning('只能上传后缀是.doc 或者 .docx 或者 .pdf 的文件 或者其它');
      }
      if (size > 30) {
        this.$message.warning('文件大小不得超过30M');
      }
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.fileList.push(file.raw) ;
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length}`);
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$message.success('文件上传成功');
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败');
    },
    // 移除文件列表时的钩子
    removeFile(file, fileList) {
      let index = this.fileList.findIndex(item => {
        return item.uid == file.uid;
      })
      this.fileList.splice(index, 1);
      this.$message.info('移除文件成功!')
    },
	//上传文件
	async uploadFile() {
      if (this.fileList.length === 0){
        this.$message.warning('请上传文件');
      }else {
        let form = new FormData();
        for (let item of this.fileList) {
          form.append('files', item)
        }
        console.log('form',form)
        if(typeof this.filePath!='number'){
          this.filePath=this.filePath[this.filePath.length-1]
        }
        this.$axios({
          method:'post',
          url: 'pm-projectManage/file/uploadFileInfo',
          headers: {
            // 'Content-Type': `multipart/form-data;boundary=${new Date().getTime()}`
            'Content-type': 'multipart/form-data;boundary=${new Date().getTime()}'
          },
          params:{
            folderId:this.filePath
          },
          data:form
        }).then(res=>{
          if(res.data.code===200){
            this.addFilesId=res.data.data.toString();
            this.upload_flag=false;
            this.$swal.fire({
              title:'上传成功',
              timer:2000,
              icon:'success'
            })
            this.fileList=[];
          }else {
            this.$swal.fire({
              title:res.data.message,
              icon:'warning',
              showConfirmButton:true
            })
            this.fileList=[];
          }
        })
      }
    },

下载文件

	 //下载文件
    async downLoadBtn(data){
      let res = await this.$axios({
        method: 'post',
        url: 'pm-projectManage/file/getFileInfo',
        responseType: "blob",
        headers:{
          'Content-Type': 'application/json'
        },
        params: {
          id: data.id,
          isOnLine: false
        }
      })
      let blob = new Blob([res.data])
      let a_link = document.createElement('a');
      // 设置下载文件名
      a_link.download = data.fileName;
      a_link.style.display = 'none';
      a_link.href = URL.createObjectURL(blob)
      document.body.appendChild(a_link);
      a_link.click();
      document.body.removeChild(a_link);
    },

在线预览文件

	// pdf加载时
    loadPdfHandler (e) {
      this.currentPage = 1 // 加载的时候先加载第一页
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage (val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        // console.log(this.currentPage)
      }
    },
    // 上一页
    prePage() {
      let page = this.currentPage
      page = page > 1 ? page - 1 : this.pageCount
      this.currentPage = page
    },
    // 图片加载成功后的回调
    success_load() {
      this.zIndex = 10000000000;
    },
    // 下一页
    nextPage() {
      let page = this.currentPage
      page = page < this.pageCount ? page + 1 : 1
      this.currentPage = page
    },
    //查看文件
    async lookFileBtn(data){
      const extFolider = ['doc', 'docx', 'xls', 'xlsx', 'pdf'];
      let extArray = ['jpg', 'jpeg', 'png', 'gif'];
      let ext = data.fileName.split('.').pop();
      if (extArray.includes(ext)) {
        this.srcList = [];
        let res = await this.$axios({
          method: 'post',
          url: 'pm-projectManage/file/getFileInfo',
          responseType: "blob",
          headers:{
            'Content-Type':"application/json;charset=UTF-8"
          },
          params: {
            id: data.id,
            isOnLine: true
          }
        })
        let blob;
        switch(ext) {
          case 'jpg':
            blob = new Blob([res.data], {
              type: "image/jpg"
            })
            this.img_dialogVisible = true;
            this.imgSrc = URL.createObjectURL(blob)
            if (this.srcList.length > 0) {
              for (let data of this.srcList) {
                if (data === this.imgSrc) return
              }
            } else {
              this.srcList.push(URL.createObjectURL(blob))
            }
            break;
          case 'jpeg':
            blob = new Blob([res.data], {
              type: "image/jpeg"
            })
            this.img_dialogVisible = true;
            this.imgSrc = URL.createObjectURL(blob)
            this.srcList.push(URL.createObjectURL(blob))
            break;
          case 'png':
            blob = new Blob([res.data], {
              type: "image/png"
            })
            this.img_dialogVisible = true;
            this.imgSrc = URL.createObjectURL(blob)
            this.srcList.push(URL.createObjectURL(blob))
            break;
          case 'gif':
            blob = new Blob([res.data], {
              type: "image/gif"
            })
            this.img_dialogVisible = true;
            this.imgSrc = URL.createObjectURL(blob)
            this.srcList.push(URL.createObjectURL(blob))
            break;
          default: console.log('未知类型文件!')
        }
      } else if(extFolider.includes(ext)) {
        this.lookVisible = true;
        let res = await this.$axios({
          method: 'post',
          url: 'pm-projectManage/file/getFileInfo',
          params: {
            id: data.id,
            isOnLine: true
          },
          headers: {
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          },
          responseType: 'blob'
        })
        console.log(res)
        let url = this.getObjectURL(res.data)
        this.src = url;
      } else {
        this.$message.warning('请下载文件进行查看!');
        this.lookVisible = false;
      }
    },
    // 将返回的流数据转换为url
    getObjectURL(file) {
      let url = null;
      if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file);
        } catch (error) {

        }
      } else if (window.URL != undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file);
        } catch (error) {

        }
      }
      return url;
    },

删除文件

	//删除文件
      deleteFile(data){
        //获取文件后缀名
        let hzName=data.fileName.substring(data.fileName.lastIndexOf(".")+1);
        //console.log(data.id)
        let extArray = ['pdf', 'doc', 'docx']
        if(data.fileName){
          if (extArray.includes(hzName)) {
            this.$swal
              .fire({
                title: '确定删除吗?',
                text: '您将无法恢复被删除的数据!',
                icon: 'warning',
                showConfirmButton: true,
                confirmButtonColor: '#DD6B55',
                confirmButtonText: '确定删除',
                reverseButtons: true,
                showCancelButton: true,
                cancelButtonText: '取消',
                cancelButtonColor: '#C1C1C1'
              }).then(async result=>{
                if (result.isConfirmed) {
                  //删除的服务器文件
                  let res = await this.$axios({
                    method: 'post',
                    url: 'pm-projectManage/file/deleteFile',
                    params: {
                      ids: data.id
                    }
                  })
                  console.log(res)
                  if (res.data.code === 200) {
                    await this.$swal.fire({
                      icon: 'success',
                      title: res.data.message,
                      timer: 2000
                    })
                    this.detailShow=false;
                  } else {
                    await this.$swal.fire({
                      icon: 'error',
                      title: res.data.message,
                      showConfirmButton: true
                    })
                  }
                  
                  let res2 = await this.$axios({
                    method: 'post',
                    url: 'pm-projectManage/contract/deleteFile',
                    data: {
                      id: this.contractId,
                      fileId:data.id
                    }
                  })
                }else {
                  return
                }
            })
          }
        }
      },
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值