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.
Why Direct Image Data Storage is Not Recommended
Base64 Encoding Issues
Some developers convert images to Base64 encoding before storing them in database fields, but this approach has the following problems:
- Field Size Limit: Database fields have size limits (e.g., 1024KB), making it impossible to store large images
- Performance Issues: Base64 encoding increases data volume by approximately 33%, affecting read/write performance
- Query Efficiency: Large fields reduce database query efficiency
- 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.)
Recommended Solution: Cloud Storage + URL
Implementation Steps
- Upload images to cloud storage
- Obtain image access URL
- 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:
- Add an "Image" type field in the data model
- When uploading images via forms or APIs, the system automatically uploads to cloud storage
- The field stores the image's fileID or URL
Image Access Methods
| Method | Description | Use Case |
|---|---|---|
| fileID | Cloud storage file unique identifier | Recommended for storage |
| Temporary Link | Valid for 2 hours | Short-term sharing |
| Permanent Link | Permanently valid | Long-term access |