纯净、安全、绿色的下载网站

首页|软件分类|下载排行|最新软件|IT学院

当前位置:首页IT学院IT技术

vue 使用OSS上传图片或附件 vue 使用OSS上传图片或附件讲解

牛先森家的牛奶   2021-09-13 我要评论
想了解vue 使用OSS上传图片或附件讲解的相关内容吗,牛先森家的牛奶在本文为您仔细讲解vue 使用OSS上传图片或附件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:vue,使用OSS上传,vue,使用OSS上传详解,下面大家一起来学习吧。

vue项目中使用OSS上传图片或附件

上传图片和附件这里不做区别;上传的流程都一样;

1、新建oss.js文件,封装使用oss (需要安装包ali-oss)

const OSS = require('ali-oss')

const OSSConfig = {
  uploadHost: 'http://xxxxx.oss-cn-shenzhen.aliyuncs.com', //OSS上传地址
  ossParams: {
    region: 'oss-cn-shenzhen',
    success_action_status: '200', // 默认200
    accessKeyId: 'LTxxxxxxxxxxxxxxxvnkD',
    accessKeySecret: 'J6xxxxxxxxxxxxxxxxiuv',
    bucket: 'xxxxxxxx-czx',
  },
}

function random_string(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function uploadOSS(file) {
  return new Promise(async (resolve, reject) => {
    const fileName = `${random_string(6)}_${file.name}`
    let client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    })
    const res = await client.multipartUpload(fileName, file)
    // resolve(res)
    // 或者返回如下:
    resolve({
        fileUrl: `${OSSConfig.uploadHost}/${fileName}`,
        fileName: file.name
    })
  })
}

export { uploadOSS }

2、页面中使用oss.js

这里是对elementUI的上传组件二次封装,里面不使用组件的action上传图片和附件,使用oss上传方式;

<template>
  <div class="upload-file">
    <el-upload
      ref="fileUpload"
      action=""
      :headers="uploadProps.headers"
      list-type="picture-card"
      :show-file-list="false"
      :http-request="fnUploadRequest"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleUpload"
    >
      <slot></slot>
    </el-upload>
  </div>
</template>

<script>
import { getAccessToken, getRefreshToken, getAccessTokenTTL } from "@/utils/auth";
import { uploadOSS } from '@/utils/oss';

export default {
  name: "index",
  data() {
    return {};
  },
  computed: {
    userAccountID() {
      return this.$store.state.user.userAccountID;
    },
    uploadProps() {
      return {
        // action: `${process.env.VUE_APP_BASE_API}/api/file/upload`,
        headers: {
          // 接口可能要带token: "",
          Authorization: getAccessToken(),
        },
        data: {},
      };
    },
  },
  methods: {
    handleExceed(file, fileList){
      // console.log(file, fileList);
      this.$message.error('上传失败,限制上传数量10个文件以内!');
    },
    handleUpload(file, fileList){
      // console.log(file, fileList);
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'docx' || testmsg === 'doc'
        || testmsg === 'pdf' || testmsg === 'zip' || testmsg === 'rar' || testmsg === 'ppt' || testmsg === 'txt'

      const isLimit10M = file.size / 1024 / 1024 < 10
      var bool = false;
      if(extension && isLimit10M){
        bool = true;
      } else {
        bool = false;
      }
      if(!extension) {
        this.$message.error('请选择附件文件类型!');
        return bool;
      }
      if(!isLimit10M) {
        this.$message.error('上传失败,不能超过10M!');
        return bool;
      }
      return bool;
    },
    handleSuccess(res) {
      // console.log(res);
      if (res) {
        this.$emit('fileData', res)
        this.$message.success("上传附件成功!");
      }
    },
    handleError(err){
      this.$message.error('上传附件失败!');
    },
    // 上传图片
    async fnUploadRequest(options) {
      try {
        // console.log(options);
        let file = options.file; // 拿到 file
        let res = await uploadOSS(file)
        console.log(res);
        // 返回数据
        this.$emit("fileData", res);
        this.$message.success("上传附件成功!");
      } catch (e) {
        this.$message.error('上传附件失败!');
      }
    },
  },
};
</script>

<style  lang="scss" scoped>
::v-deep .el-upload,
.el-upload--picture-card {
  // width: 50px;
  height: 0px;
  border: none;
  line-height: 0;
  display: block;
  background: #f5f6fb;
}
.el-upload {
  width: 50px;
}
.img-cont {
  width: 50px;
  height: 24px;
  background: #f5f6fb;
  .img-icon {
    color: #ccc;
  }
  .img-text {
    font-size: 12px;
    height: 24px;
    color: #000;
  }
}
</style>

使用封装的上传组件

  	<div class="task-detail pr">
        <el-form-item label="报备原因" prop="taskDesc" required>
          <div class="flex-center upload-position">
            <ImgUpload @imgData="imgData" />
            <FileUpload class="ml10" @fileData="fileData" />
          </div>
          <el-input
            type="textarea"
            v-model="ruleForm.taskDesc"
            placeholder="请输入报备原因"
            maxlength="200"
            @input="checkiptTaskDesc()"
          ></el-input>
          <div class="ipt-taskDesc-length">{{checkIptTaskDescLen}}/200</div>
          <div class="img-list mt10 flex">
            <ImgZoomIn :imagesList="imagesList" @deleteImg="deleteImg"></ImgZoomIn>
          </div>
          <div class="dotted-line" v-if="imagesList.length > 0 && filesList.length > 0"></div>
          <div class="file-item">
            <HandleFile :filesList="filesList" @deleteFile="deleteFile"></HandleFile>
          </div>
        </el-form-item>
      </div>

在这里插入图片描述

效果如下

在这里插入图片描述


相关文章

猜您喜欢

网友评论

Copyright 2020 www.hao45.cc 【好下载】 版权所有 软件发布

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 点此查看联系方式