2023年6月12日 星期一

AdonisJs上傳base64圖片

 小編在開發專案時遇到ReactNative套件相容問題無法取得File,因此無法正常post FormData的狀況,無奈之下只好跟前端協議改送base64編碼過來後端進行decode,在此做一下紀錄

export class AvatarUploadImageValidator {
@validate(schema.string(), {
required: File7000.IMAGE_ERROR.toString(),
string: File7000.IMAGE_ERROR.toString(),
})
public image: string
}

因為Adonisjs沒有特別驗證base64編碼,就簡單收一段文字

export default class FileService {
async uploadBase64({ base64, path, trx }) {
const [_full, contentType, image] = base64.match(/data:(image\/\w+);base64,(.*)/)
const ext = contentType.split('/')[1]
if (!ext || !contentType || !image) {
throw new ApiException(CommonCodes.FORMAT_ERROR, 'avatar image format error')
}
const decodedImage = Buffer.from(image, 'base64')

const filePath = `public/${path}/${DateTime.now().toFormat('yyyyMMddHHmmss')}_${generateCode(3)}.${ext}`
await Drive.put(filePath, decodedImage, {
contentType,
})
const fileUrl = await Drive.getUrl(filePath)
return File.create(
{
url: fileUrl,
},
{ client: trx }
)
}
}


先跟前端溝通好傳完整的編碼進來(不要只有圖片的部分),然後使用正則把需要的資訊分別提取出來,之後使用原生Buffer.from進行decode base64,剩下就是設定路徑及檔案名稱,最後再使用Adonisjs所提供的Drive進行上傳到s3,並取得網址,再來就是資料庫操作,如此打完收工。