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

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

Show input field depending on chosen option

I'm looking to create a dynamic form where specific input fields are displayed based on the selection made in another field. For example, if "gender: male" is selected, the input field for "blue" should appear, and if "gender: female" is selected, the ...

The printer is malfunctioning

My webpage has a div that includes various input fields with values assigned using jQuery. I wanted to print the contents of this div, so I found some code online to help me achieve this. However, when I try to print, the values in the input fields end up ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...

Control the data options available in the autosuggest textbox

I have implemented an autosuggest feature in a text box with predefined values. When typing the first letter in the textbox, a dropdown displays all related values. Is there a way to limit the number of displayed related values to 20? This is what my cu ...

React does not allow for images to be used as background elements

I am currently working on a web page and I have attempted to use both jpg and png images as backgrounds, but they do not seem to display on the page. import './Entrada.css' const Entrada = () => { return( <div style={{ b ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Maximizing the worth of itemtype using jQuery: A guide

My goal is to include an 'itemtype' attribute in the body tag, body.page-body.ng-scope.device-lg(itemscope='', itemtype='') I attempted the following method $('body').add(itemtype='t1'); Unfortunately, ...

Question inquired regarding a specific line of code in Javascript/Angular

While working in a factory, I am tasked with constructing an HTML page that includes a form. To successfully manipulate the form, I need to access the FormController. After conducting some research online, I managed to achieve my goal using the following l ...

Is there a way to enlarge an iFrame to fill the entire screen with just a button click, without using JavaScript

I am currently attempting to achieve full screen mode for an iFrame upon clicking a button, similar to the functionality on this site. On that website, there is a bar that expands to full screen along with the embedded game, which is what I am aiming for. ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Error: The specified module could not be found: Could not resolve 'react-hot-loader/webpack'

After constructing my React project, I encountered the error shown below. How can I resolve this issue? I am utilizing the latest version of react-hot-loader. I have attached a screenshot of the error here ...

Customize.Print - establish default print preferences

In my current project, I am exploring ways to add a print PDF feature. After discovering print.js, it seems like a possible solution for this task. My main concern is setting default print options to ensure the correct scale (i.e., 100%). Does print.js h ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

The method element.focus() is ineffective on a contentEditable div element that has been rerendered

https://example.com import React, { useEffect, useState } from "react"; import "./styles.css"; const MyCustomComponent = () => { const [text, setText] = useState(""); useEffect(() => { const textarea = documen ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

Execute jquery commands after the function has finished

I am trying to implement the code below: $(":file").change(function () { if (this.files && this.files[0]) { console.log(this.files[0]); var reader = new FileReader(); ...

Tips for relocating a CSS button

I have designed two buttons using css and I am looking to align them below the title "forecast customer activity". Due to extensive styling in css, the code might appear lengthy. Requesting assistance with a solution after reviewing the following code snip ...

Incorporating a personalized image to create custom icons on the Material UI bottom navigation bar

Is it possible to replace the default icon with a custom image in material ui's BottomNavigation component? I'm curious if Material UI supports this feature. If you'd like to take a closer look, here is the link to the codesandbox. ...