Is there a way to extract the MIME type from a base64 string?

My base64 String appears as

"UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg..."
. I am attempting to download this file using my browser. Therefore,

  1. I convert it to a blob with the following function:
      b65toBlob: function(b64Data, sliceSize = 512) {
            let byteCharacters = atob(b64Data);
            let byteArrays = [];
            for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                let slice = byteCharacters.slice(offset, offset + sliceSize);
                let byteNumbers = new Array(slice.length);
                for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }
                let byteArray = new Uint8Array(byteNumbers);
                byteArrays.push(byteArray);
            }
            let blob = new Blob(byteArrays);
            return blob;
        }
  1. Generate a URL from the blob using
    URL.createObjectURL(this.b64toBlob(base64))
  2. Simulate a click on an <a> tag with the created URL.

While Mozilla Firefox can correctly identify the file type and prompt the user to download it with the correct extension, Chrome seems to suggest downloading it as a txt file regardless of the actual file type, posing an issue.

I could specify the file type while creating the blob file to ensure that Chrome behaves properly, but I am unsure how to determine the correct MIME type from the given base64 string.

Answer №1

Start by checking the initial character of your base64 code.

text.charAt(0)

Create a switch statement with the following cases to determine the file type:

'/' : jpeg

'i' : png

'R' : gif

'U' : webp

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop RequireJS from Storing Required Scripts in Cache

It seems that RequireJS has an internal caching mechanism for required JavaScript files. Whenever a change is made to one of the required files, renaming the file is necessary in order for the changes to take effect. The typical method of adding a version ...

Implementing a JavaScript file and ensuring W3C compliance

I recently purchased a template that included a javascript file in the main page with the following code: <script src="thefile.js?v=v1.9.6&sv=v0.0.1"></script> Upon inspection, I noticed there are two arguments at the end of the file ...

Troubles with retrieving API search results using Vue computed properties

I've recently developed an Anime Search App using Vue.js and the new script setup. I'm currently struggling to access the search results in order to display the number of titles found. The app is fetching data from an external API, but it's ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Unable to establish a connection with Metamask

Looking to connect to Metamask and retrieve the account balance: <!DOCTYPE html> <html> <head> <title>Testing Ethereum with Metamask</title> <meta charset="UTF-8"> <meta name=&quo ...

How to extract part of a string delimited by certain characters within GET parameters?

I have a requirement to modify an iframe src attribute generated dynamically by a BrightCove video player. Specifically, I need to eliminate certain GET parameters such as width and height, so that the width and height of the parent element take precedence ...

The Bootstrap modal causes the scrollbar to vanish upon closure

Despite trying numerous solutions and hacks on this issue from StackOverflow, none of them seem to work for me. Currently, I am utilizing a modal for the login process in Meteor (e.g. using Facebook login service) which triggers a callback upon successful ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Leveraging functions in a Node.js module

I am struggling with using a function inside a Node.js module. I have implemented a custom sorting function to sort an array of objects based on the value of a specific property. exports.getResult = function(cards) { cards.sort(sortByField('suit& ...

When filling options within an optgroup in a selectbox, the data for each option may override one another

UPDATE: I made a change in my code: $('select[name=productSelect]').setOptions(["All products|ALL", "Products visible to all|VISIBLETOALL=1"]); I updated it to: $('select[name=productSelect]').prepend(["All products|ALL", "Product ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Successive pressing actions

I am struggling to grasp a unique Javascript event scenario. To see an example of this, please visit http://jsfiddle.net/UFL7X/ Upon clicking the yellow box for the first time, I expected only the first click event handler to be called and turn the large ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...