Skip to content

Commit

Permalink
base64 file upload blog (refinedev#1383)
Browse files Browse the repository at this point in the history
* base64 file upload blog

* Optimised images with calibre/image-actions

* Update documentation/blog/2021-12-22-base64-upload.md

Co-authored-by: Ömer Faruk APLAK <[email protected]>

* Update documentation/blog/2021-12-22-base64-upload.md

Co-authored-by: Ömer Faruk APLAK <[email protected]>

* Update documentation/blog/2021-12-22-base64-upload.md

Co-authored-by: Ömer Faruk APLAK <[email protected]>

* Update documentation/blog/2021-12-22-base64-upload.md

Co-authored-by: Ömer Faruk APLAK <[email protected]>

* update blog

* update

* Update documentation/blog/2021-12-22-base64-upload.md

* Update documentation/blog/2021-12-22-base64-upload.md

* Update documentation/blog/2021-12-22-base64-upload.md

Co-authored-by: Pankod Community Bot <[email protected]>
Co-authored-by: Ömer Faruk APLAK <[email protected]>
  • Loading branch information
3 people committed Dec 26, 2021
1 parent e537e08 commit 22f01c9
Show file tree
Hide file tree
Showing 3 changed files with 244 additions and 0 deletions.
244 changes: 244 additions & 0 deletions documentation/blog/2021-12-22-base64-upload.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
---
title: How to upload files from your HTML form using Base64 encoding
description: Uploading files using Base64 encoding is a common practice. In this guide, I'm going to show you how to upload files using base64 encoding
slug: how-to-base64-upload
authors: melih
tags: [JavaScript, how-to, base64, file-upload]
image: https://refine.dev/img/refine_social.png
hide_table_of_contents: false
---

import upload from '@site/static/img/blog/2021-12-22-base64-upload/upload.png';
import overview from '@site/static/img/blog/2021-12-22-base64-upload/overview.png';

Uploading files using Base64 encoding is a common practice. In this guide, I'm going to show you how to upload files using base64 encoding

<!--truncate-->

## What is Base64 encoding?

`Base64 Encoding` is the most widely used technique for storing or transmitting binary data by converting it to text. With this technique, binary data, which basically consists of 8-bit bytes, is divided into 6-bit (2^6 = 64) parts. 64 different numbers expressed in 6 bits are matched with 64 different characters expressed as Printable Characters in the `ASCII` character set.

Base64 encoding is most commonly used to attach binary files to electronic mail in applications of the MIME (Multipurpose Internet Mail Extensions) standard.

Another usage area of ​​Base64 Encoding is adding images and other files to HTML and CSS documents by encoding with Base64 using Data URLs format in modern browsers.

## Example

In our example, we will upload the image file by encoding the image as Base64. First, let's write simple HTML and set the [Bootstrap](https://getbootstrap.com/docs/5.1/getting-started/introduction/) CSS link.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./index.css" />
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<title>Base64 File Upload</title>
</head>

<body>
<div style="margin: 24px">
<h2>Upload Image</h2>
</div>

<script src="./index.js"></script>
</body>
</html>
```

Then we need to use the HTML [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) tag to receive an image file from the user.

We will use `file input` because it must be the input type file we want to receive.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./index.css" />
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet" />
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>

<title>Base64 File Upload</title>
</head>
<body>
<div style="margin: 24px">
<h2>Upload Image</h2>
</div>
//highlight-start
<div style="margin: 16px; padding: 16px">
<input
class="form-control form-control-lg"
id="selectAvatar"
type="file"
/>
</div>
//highlight-end
</html>
```

Now we have an input to interact with the user and select a file. Let's add the HTML elements that will show the image file and Base64 code we received from the user.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./index.css" />
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet" />
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>

<title>Base64 File Upload</title>
</head>
<body>
<div style="margin: 24px">
<h2>Upload Image</h2>
</div>

<div style="margin: 16px; padding: 16px">
<input
class="form-control form-control-lg"
id="selectAvatar"
type="file"
/>
</div>
//highlight-start
<div class="container">
<div class="row">
<div class="col">
<h6>Image Preview:</h6>
<img class="img" id="avatar" />
</div>
<div class="col">
<h6>Base64 Output</h6>
<textarea id="textArea" rows="30" cols="50"></textarea>
</div>
</div>
</div>
//highlight-end
<script src="./index.js"></script>
</body>
</html>
```

<div class="img-container">
<div class="window">
<div class="control red"></div>
<div class="control orange"></div>
<div class="control green"></div>
</div>
<img src={upload} alt="upload_screen" />
</div>
<br />

Our fields are ready to display the image file and Base64 code. Now let's do our operations on the JavaScript side.

```jsx
const input = document.getElementById("selectAvatar");
const avatar = document.getElementById("avatar");
const textArea = document.getElementById("textAreaExample");

const convertBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);

fileReader.onload = () => {
resolve(fileReader.result);
};

fileReader.onerror = (error) => {
reject(error);
};
});
};

const uploadImage = async (event) => {
const file = event.target.files[0];
const base64 = await convertBase64(file);
avatar.src = base64;
textArea.innerText = base64;
};

input.addEventListener("change", (e) => {
uploadImage(e);
});
```

Here we take data in file format and encode it as Base64. Then we show this encoded image and Base64 encoding output.

<div class="img-container">
<div class="window">
<div class="control red"></div>
<div class="control orange"></div>
<div class="control green"></div>
</div>
<img src={overview} alt="overview" />
</div>
<br />

## Live Codesandbox Example

<iframe src="https://codesandbox.io/embed/base64-upload-file-h3yy0?autoresize=1&fontsize=14&theme=dark&view=preview"
style={{width: "100%", height:"80vh", border: "0px", borderRadius: "8px", overflow:"hidden"}}
title="base64-upload-file"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>
<br/>
<br/>

## Are You Looking React Web Framework?
A React-based framework for building data-intensive applications in no time. **refine** offers lots of out-of-the box functionality for rapid development, without compromising extreme customizability. Use-cases include, but are not limited to admin panels, B2B applications and dashboards.

⚙️ Zero-configuration: One-line setup with superplate. It takes less than a minute to start a project.

📦 Out-of-the-box : Routing, networking, authentication, state management, i18n and UI.

🔌 Backend Agnostic : Connects to any custom backend. Built-in support for REST API, Strapi, NestJs CRUD, Airtable, Supabase, Appwrite and Altogic.

📝 Native Typescript Core : You can always opt-out for plain JavaScript.

🔘 Decoupled UI : UI components are exposed directly without encapsulation. You have full control on UI elements.

🐜 Powerful Default UI : Works seamlessly with integrated Ant Design System. (Support for multiple UI frameworks is on the Roadmap)

📝 Boilerplate-free Code : Keeps your codebase clean and readable.

[Refer to the **refine** documentation for more information. →](https://refine.dev/docs/getting-started/overview/)
## How to Base64 Upload with Refine?
The Base64 file upload process with **refine** is very simple. How to use it is explained step by step in the guide and example.

[Refer to the **refine** Base64 Upload guide for more information. →](https://refine.dev/docs/guides-and-concepts/upload/base64-upload/)

[View Source](https://github.com/pankod/refine/tree/master/examples/upload/base64Upload)

## Refine Base64 Upload Live Codesandbox Example
<iframe src="https://codesandbox.io/embed/refine-base64-upload-example-tm5nh?autoresize=1&fontsize=14&theme=dark&view=preview"
style={{width: "100%", height:"80vh", border: "0px", borderRadius: "8px", overflow:"hidden"}}
title="refine-base64-upload-example"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 22f01c9

Please sign in to comment.