js實現base64的轉化

2021-09-04 02:31:44 字數 3147 閱讀 4358

一、前言

1、字串轉base64。

2、base64轉字串。

3、input file選擇的轉base64。

5、input file 修改上傳型別。

二、外掛程式

將base64之間的轉化封裝成了外掛程式如下:

js外掛程式**:

// 自定義乙個類(建構函式)

function base64() else if((c > 127) && (c < 2048)) else

}return utftext;

}this._utf8_decode = function (utftext) else if((c > 191) && (c < 224)) else

}return string;

}// 定義字串轉base64的方法

this.strtobase64 = function (str) else if (isnan(chr3))

output = output +

this._keystr.charat(enc1) + this._keystr.charat(enc2) +

this._keystr.charat(enc3) + this._keystr.charat(enc4);

}return output;

}// 定義base64轉字串的方法

this.base64tostr = function (base64)

if (enc4 != 64)

}output = this._utf8_decode(output);

return output;

}// 定義轉base64的方法(filereader的方法)

this.imgtobase64fr = function (obj) )

return;

}else)}}

}}

// 定義轉base64的方法(canvas的方法)

this.imgtobase64canvas = function (obj) )

return;

}var imgurl = window.url.createobjecturl(obj.imgfile); // 將檔案建立url

// var image = document.createelement('img');

var image = new image();// 建立乙個物件

image.src = imgurl;// 對繫結src

// 當載入完畢後執行的方法,必須加這個,否則返回的width和height為0

image.onload = function() )}}

}}

html**:

預覽區域:

需要注意的是:由於用到了filereader和canvas,因此**對不支援這兩種的瀏覽器不相容。

三、預覽

將轉化的base64**顯示到img標籤中。

var preview = document.queryselector(".preview img");

preview.src = res.data// res.data是轉的base64**

四、input file的上傳型別

這是支援的檔案型別(從網上找的,沒有乙個個測驗,慎用)

通過修改accept的值,僅僅是修改了選擇的顯示型別,並不代表不能選擇其他型別。

真正的限制上傳型別,還需要通過**判斷檔案型別進行篩選。

BASE64演算法實現

cstring base64encode lpctstr lpszsrc 56 63 unsigned int itest lpctstr pinbuffer lpszsrc int nsize int tcslen lpszsrc char poutbuffer new char nsize 3 ...

base64編碼實現

package com.ls.hfvj 思路 base64只有64個字元,因此只需要6個二進位制位來表示 實現 每3個位元組為一組湊4個base64字元。多餘乙個位元組補4個0bit位 共12位 湊成2個base64字元 多餘兩個位元組補2個bit位 共18位 湊成3個base64字元。為了知道新增...

base64轉化為blob,blob轉化為file

背景 最近在做乙個移動端手寫簽名的功能。需求是將手寫簽名生成存到後台,實現步驟 canvas畫圖,生成base64,將base64轉為file物件。1,canvas具體怎麼實現手寫簽名,不在細講,主要是touchmove.touchstart,touchend事件和canvas畫筆工具結合,生成ba...