10 examples of 'convert file to base64 javascript' in JavaScript

Every line of 'convert file to base64 javascript' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
12function base64_encode(file) {
13 var bitmap = fs.readFileSync(file);
14 var h;
15 if (file.endsWith(".png")) {
16 h = "data:image/png;base64, ";
17 } else {
18 h = "data:image/jpeg;base64, ";
19 }
20 return h + Buffer.from(bitmap).toString("base64");
21}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

5export function fileToBase64(file: File): Promise<Data> {
6
7 return new Promise<Data>((resolve, reject) => {
8 if (!/^image\/\w+$/.test(file.type)) {
9 reject('Invalid image file');
10 }
11
12 const reader = new FileReader();
13 reader.onload = (e) => {
14 const img = new Image();
15 const fileData = (e.target as any).result;
16
17 img.onload = () => {
18 resolve({
19 url: fileData,
20 data: fileData.split(',')[1],
21 filename: file.name,
22 contentType: file.type,
23 width: img.width,
24 height: img.height
25 });
26 };
27
28 try {
29 img.src = fileData;
30 } catch (e) {
31 reject(e);
32 }
33 };
34 reader.readAsDataURL(file);
35 });
36}
277async function fileToBase64(filePath: string) {
278 const data = await new Promise<Buffer>((resolve, reject) => {
279 readFile(filePath, (err, data) => {
280 if (err) {
281 return reject(err);
282 }
283 resolve(data);
284 });
285 });
286 return data.toString("base64");
287}
126function encodeBase64 (filePath, callback) {
127 var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox; // save original sandbox value
128 var errorHandler = function (err) {
129 var msg = 'An error occured: ';
130
131 switch (err.code) {
132 case FileError.NOT_FOUND_ERR:
133 msg += 'File or directory not found';
134 break;
135
136 case FileError.NOT_READABLE_ERR:
137 msg += 'File or directory not readable';
138 break;
139
140 case FileError.PATH_EXISTS_ERR:
141 msg += 'File or directory already exists';
142 break;
143
144 case FileError.TYPE_MISMATCH_ERR:
145 msg += 'Invalid file type';
146 break;
147
148 default:
149 msg += 'Unknown Error';
150 break;
151 }
152
153 // set it back to original value
154 window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
155 callback(msg);
156 };
157 var gotFile = function (fileEntry) {
158 fileEntry.file(function (file) {
159 var reader = new FileReader();
160
161 reader.onloadend = function (e) {
162 // set it back to original value
163 window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
164 callback(this.result);
165 };
166
167 reader.readAsDataURL(file);
168 }, errorHandler);
169 };
170 var onInitFs = function (fs) {
171 window.qnx.webplatform.getController().setFileSystemSandbox = false;
172 fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
173 };
174
175 window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max
176}
34function decodeBase64 (fileContent) {
35 var buf = new Buffer(fileContent, 'base64');
36 return buf.toString();
37}
18function jsToUrl(path, js) {
19 var url = urls[path];
20 if (url) window.URL.revokeObjectURL(url);
21 var blob = new Blob([js], { type: "application/javascript" });
22 return (urls[path] = window.URL.createObjectURL(blob));
23}
181function getBase64Contents(contents) {
182 return contents.replace(/^data:image\/(jpeg|png)+;base64,/, '');
183}
14function _arrayBufferToBase64(buffer) {
15 var binary = '';
16 var bytes = new Uint8Array(buffer);
17 var len = bytes.byteLength;
18 for (var i = 0; i < len; i++) {
19 binary += String.fromCharCode(bytes[i]);
20 }
21 return btoa(binary);
22}
32function base64Decode(base64) {
33 base64 = base64.replace(/\*/g,'+').replace(/-/g,'/').replace(/\_/g,'=');
34 let result = new Buffer(base64, 'base64').toString();
35 return result;
36}
285getBase64(src, { width, height, x, y }) {
286 return new Promise((resolve, reject) => {
287 const img = new Image();
288 img.crossOrigin = 'Anonymous'; // 允许跨域
289 img.onload = () => {
290 const canvas = $('<canvas width="' + width + '" height="' + height + '"></canvas>')[0];
291 const ctx = canvas.getContext('2d');
292 ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
293 resolve(canvas.toDataURL());
294 };
295 img.onerror = err => {
296 console.error('图片转base64失败!');
297 reject(err);
298 };
299 img.src = src + '?t=' + this.randomID();
300 });
301}

Related snippets