Frontend Development 5 min read

Identifying and Converting Between Base64, Blob, and File in JavaScript

This guide explains the characteristics of Base64 strings, Blob objects, and File objects in web development, shows how to detect each type in JavaScript, and provides conversion functions to transform between Base64, Blob, and File formats.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Identifying and Converting Between Base64, Blob, and File in JavaScript

In this article the author explains the three common data formats used in web development—Base64 strings, Blob objects and File objects—describes their characteristics, shows how to determine which type a given variable is, and provides JavaScript functions to convert between them.

Base64 is a widely used encoding that represents binary data using 64 printable characters. Example image shown.

Blob represents immutable raw binary data; it can be read as text or binary and can be converted to a ReadableStream .

File extends Blob and adds metadata such as name and last modified date, allowing JavaScript to access file contents.

Detection methods:

Base64: use a regular expression test, e.g. function isBase64(str) { var reg = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/\?%\s]*?)\s*$/i; return reg.test(str); }

Blob: console.log(data instanceof Blob); // true or false

File: console.log(data instanceof File && !(data instanceof Blob)); // true or false

Conversion functions:

Base64 → File: function dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type: mime}); }

Base64 → Blob: function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type: mime}); }

Blob → File: function blobToFile(blob) { return new File([blob], 'screenshot.png', {type: 'image/jpeg'}); }

Note that File inherits from Blob , so instanceof Blob returns true for File objects as well; custom logic may be needed to distinguish them.

frontendJavaScriptblobBase64conversionfile()
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.