vue 图片上传到阿里OSS

<script>
    export default {
        data() {
            return {
                oss: {} //上传阿里的信息
            };
        },
        mounted() {
            // 调取上传图片到服务器的接口,获取oss信息
            this.axios.post('api/upload/sts').then(res => {
                if (res.status == 1) {
                    this.oss = res.data;
                }
            });
        },
        methods: {
            // 点击上传图片
            upfile(e) {
                let file = e.target.files[0];
                let OSS = require("ali-oss");
                const client = new OSS({
                    region: "oss-cn-shenzhen",
                    accessKeyId: this.oss.AccessKeyId,
                    accessKeySecret: this.oss.AccessKeySecret,
                    stsToken: this.oss.SecurityToken,
                    bucket: this.oss.bucket
                });

                // 压缩
                lrz(file).then(function(rst) {
                    //  文件名:图片名字加上时间戳和9999以内随机数,防止重名
                    const imgName =`member_photo/${new Date().getTime()}${Math.floor(Math.random() * 10000)}${rst.origin.name}`;
                    // base64格式的图片文件
                    let urlData = rst.base64;
                    const base64 = urlData.split(",").pop();
                    const fileType = urlData.split(";").shift().split(":").pop();
                    // base64转blob
                    const blob = this.dataURLtoBlob(base64, fileType);
                    // blob转arrayBuffer
                    const reader = new FileReader();
                    reader.readAsArrayBuffer(blob);
                    reader.onload = event => {
                        // arrayBuffer转Buffer
                        const buffer = new OSS.Buffer(event.target.result);
                        // 上传
                        client.put(imgName, buffer)
                            .then( result=> {
                                console.log("上传成功后返回的url", result.url);
                            })
                            .catch( err=> {
                                console.log("错误", err);
                            });
                    };
                });
            },
            
            // base64转blob
            dataURLtoBlob(urlData, fileType) {
                let bytes = window.atob(urlData);
                let n = bytes.length;
                let u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bytes.charCodeAt(n);
                }
                return new Blob([u8arr], {
                    type: fileType
                });
            }
        }
    }
</script>
发布了76 篇原创文章 · 获赞 144 · 访问量 2970

猜你喜欢

转载自blog.csdn.net/qq_40745143/article/details/103920811