JS base64 圖片上傳

毛仔發表於2018-10-26
// 定義上傳事件
            $('.upload').click(function(){

                // 將base64檔案轉換為bolb檔案
                function getBlobBydataURI(dataURI,type) {
                    var binary = atob(dataURI.split(',')[1]);
                    var array = [];
                    for(var i = 0; i < binary.length; i++) {
                        array.push(binary.charCodeAt(i));
                    }
                    return new Blob([new Uint8Array(array)], {type:type });
                }

                $.ajax({
                   url:'/getQiniuToken2',
                    type:'get',
                    success:function(data){
                        var formData = new FormData();
                        var $Blob= getBlobBydataURI(img,'image/jpeg');
                        formData.append('file',$Blob);
                        var timestamp = new Date().getTime();
                        formData.append('key',timestamp + '.png');
                        formData.append('token',data.uptoken);

                        $.ajax({
                            url:'http://upload.qiniu.com/',
                            type:'post',
                            data:formData,
                            async: true,
                            crossDomain: true,
                            contentType: false,
                            processData: false,
                            success:function(data){
                                var url = 'http://osibaji20.bkt.clouddn.com/'+data.key;
                                console.log(url);
                            },
                            error:function(error){
                                console.log(error);
                            }
                        })
                    }
                });
//
                })
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章