Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Last active July 27, 2024 19:53
Show Gist options
  • Save jdnichollsc/f10638d44f0a9cc6bd03a1733c896f39 to your computer and use it in GitHub Desktop.
Save jdnichollsc/f10638d44f0a9cc6bd03a1733c896f39 to your computer and use it in GitHub Desktop.
Upload Base64/Blob files to Google Cloud Storage
import { join } from 'path'
import { get } from 'lodash'
import { Storage } from '@google-cloud/storage'
import { BUCKET_NAME } from '../constants'
import { base64MimeType } from '../utils'
const gcloudPathKey = join(__dirname, '../gcloud-key.json')
const storage = new Storage({
projectId: 'my-project-id',
keyFilename: gcloudPathKey
})
export const uploadAndGetPublicFile = async (
fileName: string,
data: Blob | string,
defaultMimeType?: string
) => {
const [bucketExist] = await storage
.bucket(BUCKET_NAME)
.exists();
if (!bucketExist) {
await storage.createBucket(BUCKET_NAME);
}
const file = storage
.bucket(BUCKET_NAME)
.file(fileName);
const fileOptions = {
public: true,
resumable: false,
metadata: { contentType: base64MimeType(data) || defaultMimeType },
validation: false
}
if (typeof data === 'string') {
const base64EncodedString = data.replace(/^data:\w+\/\w+;base64,/, '')
const fileBuffer = Buffer.from(base64EncodedString, 'base64')
await file.save(fileBuffer, fileOptions);
} else {
await file.save(get(data, 'buffer', data), fileOptions);
}
const publicUrl = `https://storage.googleapis.com/${BUCKET_NAME}/${fileName}`
const [metadata] = await file.getMetadata()
return {
...metadata,
publicUrl
}
}
export default storage
export function base64MimeType(encoded: any): string {
var result = null;
if (typeof encoded !== 'string') {
return result;
}
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
if (mime && mime.length) {
result = mime[1];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment