Ali cloud oss Vue achieve file upload (after the signature server forward pass)

Reference website: https://help.aliyun.com/document_detail/31926.html

<template>
    <div class="test">
        <div>
                
            <input type="file" id="file" name="file" />
            <a @click="upload()" href="javascript:;">上传</a>

        </div>
    </div>
</template>



<script>
export default {
    data(){
        return {

        }
    },
    mounted() {
    
        this.getOssToken();
    },
    methods: {
        //获取上传通行证
        getOssToken(){
            var _self = this;
            this.$http.get('/api/v1/alioss/sign').then(function(res){
                if(res.data.code == 200){
                    _self.aliyunOssToken = res.data.data;
                }else{
                    _self.$message.error(res.data.message);
                }
            }).catch(function(error){
                console.log(error);
            })
        },

        upload(){
            var _self = this;
            var getSuffix = function (fileName) {
                var pos = fileName.lastIndexOf(".");
                var suffix = '';
                if (pos != -1) {
                    suffix =fileName.substring (POS); 
                }
                return suffix; 
            } 

            var File = $ ( " #file " ) .val ();
             IF (file.length ==  0 ) { 
                Alert ( " Please select a file " ); 
            } 

            var filename =  new new a Date () the getTime (). + getSuffix (File);
             var formData =  new new the formData (); 

            // note that in the case of bond formData append added 
            formData.append ( ' key ' , _self.aliyunOssToken.dir+ filename); //存储在oss的文件路径
            formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
            formData.append('policy', _self.aliyunOssToken.policy); //policy
            formData.append('Signature', _self.aliyunOssToken.signature); //签名
            formData.append("file", $("#file")[0] .files [ 0 ]);
            formData.append ( ' success_action_status ' , 200 is ); // returns after a successful operation code 


            var URL = _self.aliyunOssToken.host;
             var fileURL = _self.aliyunOssToken.host + ' / ' + _self.aliyunOssToken. the dir + filename; 
            $ .ajax ({ 
                URL: URL, 
                type: ' the POST ' , 
                Data: formData, 
                // the async: to false, 
                Cache: to false ,
                contentType: false,
                processData: false,
                success: function (data) {
                    console.log(fileUrl);
                    console.log(data);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }
    }
}
</script>

 

Guess you like

Origin www.cnblogs.com/zion0707/p/10974556.html