vant-uiアップロードファイルコンポーネント、base64データストリームアップロードali-oss

vant-uiコンポーネントを使用して画像をアップロードすると、返される画像はbase64形式になります

<van-field name="uploader" label="作品封面">
                    <template #input>
                      <van-uploader :max-count='1' v-model="uploader" :after-read="afterRead"> </van-uploader>
                    </template>
                </van-field>

ここに画像の説明を挿入
ここに画像の説明を挿入
現時点では、base64形式での画像のアップロードは成功せず、次の情報が表示されます:
put用のBuffer / Blob / Fileを提供する必要があります。
ここに画像の説明を挿入
私の解決策は、base64をblobオブジェクト、arrayBufferオブジェクト、bufferオブジェクトに変換してからアップロードすることです。結果のバッファオブジェクトは、コード上で問題ありません。

afterRead(file) {
    
    
            const fileN = file.content;   //上面图片中有
            const fileU = file.file.name;  //上面图片中有
            const base64 = fileN.split(',').pop();
            const fileType = fileN.split(';').shift().split(':').pop();
            const blob = this.toBlob(base64, fileType)
            //blob转arrayBuffer
            const reader = new FileReader();
            reader.readAsArrayBuffer(blob);

            reader.onload = function(event) {
    
    
                const fileExtension = fileU.substring(fileU.lastIndexOf('.'));
                //uuid是一个生成随机数的函数,下面贴
                const objectKey = 'gt/' + uuid() + fileExtension;
                //arrayBuffer转buffer
                const buffer = new OSS.Buffer(event.target.result);
				//client是ali-oss的相关配置
                client.put(objectKey , buffer).then(result => {
    
    
                    console.log(result)
                    this.imageUrl = result.url;
                    console.log(this.imageUrl)
                }).catch(err => {
    
    
                    console.log(err)
                })
            }
        },
        //转bolb对象
        toBlob(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 });
        },

最後に、結果によって返される結果を見てください:
ここに画像の説明を挿入
それは成功しました

function uuid() {
    
     //生成随机数

    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
    
    
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}
let client = new OSS({
    
    
    region: 'xxx',
    accessKeyId: 'xxxx',
    accessKeySecret: 'xxxx',
    bucket: 'xxx',
    endpoint: 'xxx',
    cname: true,
});

新しいFileReader()が非同期であり、onloadイベントの外部で実行結果を取得できないという別の問題があることがわかりました。FileReader()を関数でカプセル化するようにコードを変更し、
完全なPromiseコードを返します。

afterRead(file) {
    
     //上传封面图片到ali-oss
            const fileN = file.content;
            const fileU = file.file.name;
            const base64 = fileN.split(',').pop();
            const fileType = fileN.split(';').shift().split(':').pop();
            const blob = this.toBlob(base64, fileType)
            this.readFile(blob).then(res => {
    
    
                const fileExtension = fileU.substring(fileU.lastIndexOf('.'));
                const objectKey = 'gt/' + uuid() + fileExtension;
                const buffer = new OSS.Buffer(res.target.result);
                client.put(objectKey, buffer).then(result => {
    
    
                    console.log(result)
                    this.imageUrl = result.url;
                    console.log(this.imageUrl)
                }).catch(err => {
    
    
                    console.log(err)
                })
            })
        },
        readFile(file) {
    
    
            return new Promise((resolve, reject) => {
    
    
                const reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = function(event) {
    
    
                    resolve(event)
                }
            })
        },
        toBlob(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 });
        },

問題は解決しました

おすすめ

転載: blog.csdn.net/YL971129/article/details/113926092