Base64 versus UTF-8 charset: What sets them apart?

While working with binary files, I discovered that:

  • If it's a text-based file, I need to use data:text/plain;charset=utf-8,
  • and if it's a multimedia file, I should use data:image/png;base64,

I attempted to use base64 encoding and encountered an error when trying to download a file using the following syntax.

<a href="data:text/plain;base64,VGVzdCBEb2N1bWVudA%3D%1E" download="sample text.txt">download</a>

The script used to generate the above code is as follows:

<script>
var filecontent = binaryAgent("010101100100011101010110011110100110010001000011010000100100010101100010001100100100111000110001011000100101011101010110011101010110010001000001001111010011110");
download("sample text.txt", filecontent, "data:text/plain;base64,");
function binaryAgent(str) {
          // Removes the spaces from the binary string
          str = str.replace(/\s+/g, '');
          // Pretty (correct) print binary (add a space every 8 characters)
          str = str.match(/.{1,8}/g).join(" ");

          var binString = '';

          str.split(' ').map(function(bin) {
              binString += String.fromCharCode(parseInt(bin, 2));
          });

          return binString;
        }

        function download(filename, text, encodedType) {
          var element = document.createElement('a');
          element.setAttribute('href', encodedType + encodeURIComponent(text));
          element.setAttribute('download', filename);

          element.style.display = 'none';
          document.body.appendChild(element);

          element.click();

          document.body.removeChild(element);
        }
</script>

What makes these two types different? Can base64 be used for text-based files as well?

Answer №1

It appears that you have created an incorrect base64 string, please update the

data:text/plain;base64,VGVzdCBEb2N1bWVudA%3D%1E

to

data:text/plain;base64,VGVzdCBEb2N1bWVudA

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

create a nested promise with a delay in a node.js environment

Utilizing Google geocoding in my coding tasks has presented a challenge. I have around 50 places to geocode, but Google restricts the number of places that can be geocoded simultaneously, resulting in an 'OVER_QUERY_LIMIT' error. To address this ...

Access the Windows directory through a custom HTML link

Currently, I am in the process of creating a personalized "website" that contains a collection of links leading to specific items on my computer. When I click on a link, the folder opens within the browser. Is there a way for these links to open Windows Ex ...

Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename. Can someone assist me with this? Here is a Js fiddle that I've been working on. This is my HTML mark ...

Struggling to get collapsible feature functioning on website

I'm trying to create a collapsible DIV, and I found a solution on Stack Overflow. However, I'm having trouble getting it to work on my website. I created a fiddle with the full code, and it works there. But when I implement it on my site, the con ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

The issue of nested form serialization not functioning properly in JQuery has been identified

I am currently in the process of developing a web application. One particular page within this application contains a form, called form1, and I am inserting another page with its own form, form2, inside of form1. Each form contains their own set of values. ...

Changing Float Attributes to String in Google Earth Engine

I am trying to export data from Google Earth Engine to my Google Drive. To name the file, I am using information from its data properties which results in 2019.0_1.0. However, I would like the file name to be in a different format - '2019_1'. Bel ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

Embrace the flexibility of using Next.js with or without Express.js

Recently, I started the process of migrating a project from create-react-app to next.js. However, I am facing uncertainty when it comes to migrating the backend of the project. Currently, my backend is built with an express server. In next.js, there are p ...

The print preview displays a single div in an incorrect location

I have successfully created a javascript plot and wanted to incorporate a legend that overlaps the plot. Unfortunately, the function I used does not support directly overlapping legends, but it does allow for placing the legend in a separate div. To work a ...

Is there a way to automatically update the state in ReactJS whenever new information is added or deleted, without the need to manually refresh the page

I have encountered an issue that I have been trying to resolve on my own without success. It seems that the problem lies in not updating the Lists New state after pushing or deleting from the API. How can I rectify this so that manual page refreshing is no ...

Error: JSON parsing encountered an issue with token "o" at position 1 while making an ajax request

When I try to make an AJAX call, my code is set up like this: var Data = { name : $('input[name=name]').val(), email : $('input[name=email]').val(), phoneno : $('input[nam ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

React Alert: "Unable to modify while in the middle of a state transition"

Currently, I am working on developing an application that involves utilizing a toastr component. However, I am encountering an error when attempting to dispatch a redux action within this particular component. The error message displayed in the console is ...

Generate an image instantly from text using ajax when a key is pressed

Currently, I am immersed in a stencil project where my goal is to convert text into an image. In this particular task, there's a textbox that captures the user input on key up event. Once the user enters text, my aim is to display that text as an imag ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

Is it possible to switch the background-image after a gif has finished loading?

I am currently using a GIF as a background image, but I would like it to show a static image until the GIF is fully loaded and ready to play. After reading several similar discussions, I understand that you can manipulate elements with JavaScript once the ...

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

AngularJS: Error - Angular object is undefined

Hello! I am currently working on a project to develop a simple App using c# WebAPI and AngularJS. Unfortunately, I have encountered an error in the console which is preventing the web app from functioning properly. Here is a snippet of my Index.html file: ...