通常在做前端开发时,对于文件上传的功能,通常把那些大文件的视频或者音频一般是传到阿里云或者腾讯云,因为这样也可以减少公司本地服务器的空间,举个例子阿里云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数据属性中。
你可以根据自己的项目需求对该示例进行调整和扩展。