Vue项目中使用upload组件上传图片,视频到OSS阿里云服务器

Vue项目中使用upload组件上传图片,视频到OSS阿里云服务器

项目中使用vue搭配elementui组件库的upload完成图片文件视频的上传,项目中是上传到OSS

了解upload组件

upload大家都不陌生,这里就不详细介绍了,大家可以到官网查看详细文档------element-upload文档

   //注意 action 属性必须要有,这里我们是上传OSS,不做固定
	   
       <el-form-item label="视频封面: ">
          <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            accept=".jpg,.png"
            :before-upload="beforeUploadImage"
            name="file"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="上传视频: ">
          <el-upload
            class="upload-demo"
            action
            accept=".mp4,.ogg,.flv,.avi,.wmv,.rmvb"
            :limit="1"
            :file-list="fileList"
            :show-file-list="true"
            :before-upload="beforeUploadVideo"
            name="file"
          >
            <el-button size="small" type="primary">点击上传视频</el-button>
            <span slot="tip" class="el-upload__tip">
              可上传视频文件格式: mp4/ogg/flv/avi/wmv/rmvb
            </span>
          </el-upload>
        </el-form-item>

首先我们要获取oss上传参数(页面加载就要获取)

 // 获取oss上传参数
    getOssParams () {
      formattingApi({ dirName: 'xly' }).then(response => {
        this.ossParamsObj = response  //ossParamsObj是对象格式的
      })
    },

上传oss文件方法

 upOssFile (resData, fileInfo) {
      // 拦截 XHR
      // if (XHR) window.XMLHttpRequest = XHR
      return new Promise((resolve, reject) => {
        let fileObj = new FormData()
        fileObj.append("OSSAccessKeyId", resData.OSSAccessKeyId)
        fileObj.append("accessKey", resData.accessKey)
        fileObj.append("bucket", resData.bucket)
        fileObj.append("expire", resData.expire)
        fileObj.append("host", resData.host)
        fileObj.append("key", resData.key + "/" + fileInfo.oGetTime)
        fileObj.append("policy", resData.policy)
        fileObj.append("signature", resData.signature)
        fileObj.append("file", fileInfo.file)
        fileObj.append("name", fileInfo.name)
        fileObj.append("type", fileInfo.type)
        fileObj.append("lastModifiedDate", fileInfo.lastModifiedDate)
        fileObj.append("size", fileInfo.size)
        axios.post(resData.host, fileObj).then(() => {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },

上传图片视频

  // 上传视频封面
    beforeUploadImage (file) {
      this.binary = file
      let oGetTime = new Date().getTime()
      this.upOssFile(this.ossParamsObj, {
        file: this.binary,
        name: file.name,
        type: file.type,
        lastModifiedDate: file.lastModifiedDate,
        size: file.size,
        oGetTime: oGetTime,
      }).then(() => {
        this.imageUrl = `${this.ossParamsObj.host}${this.ossParamsObj.key}/${oGetTime}`
        this.binary = null
      })
      return false
    },
    // 上传视频
    beforeUploadVideo (file) {
      this.binary = file
      let oGetTime = new Date().getTime()
      this.upOssFile(this.ossParamsObj, {
        file: this.binary,
        name: file.name,
        type: file.type,
        lastModifiedDate: file.lastModifiedDate,
        size: file.size,
        oGetTime: oGetTime,
      }).then(() => {       
        this.binary = null
        this.fileList.push({ name: file.name })
        this.videoUrl = `/${this.ossParamsObj.key}/${oGetTime}`
      })
      return false
    },

点击确定上传文件

// 点击确定上传
    imageVideoUpLoad () {
      if (!this.popTitle) {
        this.$message.error('请添加视频标题! ')
        return false
      }
      if (!this.imageUrl) {
        this.$message.error('请上传视频封面图片! ')
        return false
      }
      if (!this.videoUrl) {
        this.$message.error('请上传视频! ')
        return false
      }
      upLoadVideoApi({
        title: this.popTitle,
        picture: this.imageUrl,
        url: this.videoUrl,
      }).then(res => {
        this.dialogFormVisible = false
        this.$message.success('上传成功! ')
        this.getVideoList()
      })
    },

方法比较笨可能,不过上传oss是没有问题的,大家有更好的方法可以留言交流噢 !

Vue.js项目中,实现图片文件上传至阿里云OSS(Object Storage Service)通常涉及以下几个步骤: 1. **安装依赖**: 首先,需要安装`axios`用于发送HTTP请求和`ali-oss`库,它是官方推荐的阿里云OSS SDK: ```bash npm install axios ali-oss ``` 2. **配置阿里云OSS**: 创建一个新的OSS客户端,并设置您的Access Key ID、Secret Access Key和Bucket名称。这通常在项目的配置或环境变量中管理。 3. **组件编写**: 在Vue组件中,可以创建一个文件输入元素(例如`<input type="file">`),当用户选择文件后,使用`axios`发起PUT请求上传OSS: ```javascript methods: { uploadImage(file) { const ossClient = new OSS({ region: 'your-region', // 您的阿里云区域 accessKeyId: 'your-access-key-id', accessKeySecret: 'your-secret-access-key', bucket: 'your-bucket-name' }); const uniqueName = generateUniqueFileName(file.name); // 生成唯一文件名 ossClient.put(uniqueName, file) .then(response => { console.log('Upload successful:', response); // 返回OSS URL,可以在前端展示或保存 return `https://your-bucket-name.oss-cn-your-region.aliyuncs.com/${uniqueName}`; }) .catch(error => { console.error('Error uploading:', error); }); }, } ``` 4. **处理错误**: 考虑到网络状况或权限问题,确保捕获并适当地处理可能出现的错误。 5. **安全提示**: 尽量不要直接在HTML模板中显示OSS链接,因为这可能导致暴露敏感信息。考虑在后端生成URL,通过API返回给前端展示。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值