Skip to main content

Best Practice for Storing Images in Database

When storing images in CloudBase, it's recommended to save image files to cloud storage and then store the image URL in the database field.

Base64 Encoding Issues

Some developers convert images to Base64 encoding before storing them in database fields, but this approach has the following problems:

  1. Field Size Limit: Database fields have size limits (e.g., 1024KB), making it impossible to store large images
  2. Performance Issues: Base64 encoding increases data volume by approximately 33%, affecting read/write performance
  3. Query Efficiency: Large fields reduce database query efficiency
  4. Traffic Consumption: Each record read transfers the complete image data

Binary Data Issues

Directly storing image binary data is also not recommended:

  • Databases are not suitable for storing large binary objects
  • Cannot leverage CDN acceleration
  • Does not support image processing (scaling, cropping, etc.)

Implementation Steps

  1. Upload images to cloud storage
  2. Obtain image access URL
  3. Store URL in database field

Mini Program Example

// 1. Select image
const res = await wx.chooseImage({
count: 1
});
const filePath = res.tempFilePaths[0];

// 2. Upload to cloud storage
const uploadRes = await wx.cloud.uploadFile({
cloudPath: `images/${Date.now()}.jpg`,
filePath: filePath
});
const fileID = uploadRes.fileID;

// 3. Get temporary access link (optional, for preview)
const urlRes = await wx.cloud.getTempFileURL({
fileList: [fileID]
});
const tempUrl = urlRes.fileList[0].tempFileURL;

// 4. Save fileID to database
await db.collection('articles').add({
data: {
title: '文章标题',
coverImage: fileID // Store fileID
}
});

Web Example

import cloudbase from '@cloudbase/js-sdk';

const app = cloudbase.init({ env: 'your-env-id' });

// Upload image
async function uploadImage(file) {
const result = await app.uploadFile({
cloudPath: `images/${Date.now()}_${file.name}`,
filePath: file
});
return result.fileID;
}

// Save to database
async function saveArticle(title, imageFile) {
const fileID = await uploadImage(imageFile);

await app.database().collection('articles').add({
title: title,
coverImage: fileID
});
}

Data Model Image Field

If using data models, you can use the "Image" field type, which automatically handles image upload and URL storage:

  1. Add an "Image" type field in the data model
  2. When uploading images via forms or APIs, the system automatically uploads to cloud storage
  3. The field stores the image's fileID or URL

Image Access Methods

MethodDescriptionUse Case
fileIDCloud storage file unique identifierRecommended for storage
Temporary LinkValid for 2 hoursShort-term sharing
Permanent LinkPermanently validLong-term access