Skip to content
Advertisement

Should i convert a file to Base64 before or after sending it to the backend?

First of all, i am aware that saving a Base64 string in the database is not the most efficient way to save images, but i do not have a lot of them and load them rarely, so that should not be a problem.

So lets start, i have a SQL database with a table “pictures” which has two column, a unique name and a string representing a file in base 64:

@Entity
public class Picture {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column(unique = true)
  private String name;
  private String imageInBase64;
}

A user is able to select an image in the user interface which then gets send to the backend via REST. My question is, should i encode the file/picture to Base64 before sending it to the backend or should i encode it in the backend after receiving it? Currently i just encode it in the frontend and send a JSON representing the Picture class.

Advertisement

Answer

This is from this post… Storing image in database directly or as base64 data?

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

While base64 is fine for transport, do not store your images base64 encoded.

Base64 provides no checksum or anything of any value for storage.

Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It’s generally faster to read fewer bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you’re regularly outputting the image in base64, then consider storing in base64.

Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves–you’re sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).

If you still wish to store images base64 encoded, please, whatever you do, make sure you don’t store base64 encoded data in a UTF8 column then index it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement