阿里云OSS文件上传

通常在做前端开发时,对于文件上传的功能,通常把那些大文件的视频或者音频一般是传到阿里云或者腾讯云,因为这样也可以减少公司本地服务器的空间,举个例子阿里云OSS文件上传的步骤

<template>
  <div>
    <h1>阿里云OSS文件上传示例</h1>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">上传文件</button>
    <div v-if="uploadProgress > 0">
      上传进度: {{ uploadProgress }}%
    </div>
    <div v-if="uploadResult">
      文件上传成功!
      文件URL: {{ uploadResult.url }}
    </div>
  </div>
</template>

<script>
import OSS from 'ali-oss';

export default {
  data() {
    return {
      file: null,
      uploadProgress: 0,
      uploadResult: null
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    uploadFile() {
      if (!this.file) {
        return;
      }

      // 初始化OSS对象
      const client = new OSS({
        accessKeyId: 'your-access-key-id',
        accessKeySecret: 'your-access-key-secret',
        region: 'your-oss-region',
        bucket: 'your-bucket-name'
      });

      // 设置上传回调函数
      const options = {
        progress: (percentage, checkpoint, res) => {
          this.uploadProgress = Math.floor(percentage * 100);
        }
      };

      // 开始文件上传
      client.put('your-oss-path/' + this.file.name, this.file, options)
        .then(result => {
          this.uploadResult = result;
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};
</script>




请确保在使用之前先安装ali-oss库,并替换代码中的your-access-key-id、your-access-key-secret、your-oss-region和your-bucket-name与有效的阿里云OSS信息。

在该示例中,我们通过<input type="file">标签选择文件,
并通过handleFileChange方法将文件保存到file数据属性中。
然后,我们通过点击<button>触发uploadFile方法,该方法使用阿里云OSS SDK将文件上传到阿里云OSS,
并通过数据属性uploadProgress跟踪上传进度,最后将上传结果保存到uploadResult数据属性中。

你可以根据自己的项目需求对该示例进行调整和扩展。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值