Skip to content

Commit

Permalink
Merge pull request #1319 from gagansuie/dev
Browse files Browse the repository at this point in the history
Fix: testing base64string conversion
  • Loading branch information
gagansuie authored Jul 15, 2024
2 parents 80fdbd6 + c4f024a commit 8beac24
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 15 deletions.
32 changes: 30 additions & 2 deletions src/lib/components/Profile/DrawerEditProfile.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { page } from '$app/stores'
import DrawerAddCategory from '$lib/components/Browse/DrawerAddCategory.svelte'
import { category_list } from '$lib/stores/channelStore'
import { createEffect, objectMonitor, isValidUrl } from '$lib/utils'
import { createEffect, objectMonitor, isValidUrl, fileToBase64 } from '$lib/utils'
export let showDrawer: boolean
export let profile: any
Expand Down Expand Up @@ -109,7 +109,35 @@
class="flex h-full p-5"
action="?/update-profile"
method="post"
use:enhance={({ formData }) => {
use:enhance={async ({ formData }) => {
let avatar = formData.get('avatar') || null
if (avatar != null && avatar instanceof File && avatar.size > 0) {
await fileToBase64(avatar)
.then((base64String) => {
if (base64String) {
formData.set('avatar', base64String)
}
})
.catch((error) => {
console.error('Error converting file to base64:', error)
})
} else {
formData.delete('avatar')
}
let banner = formData.get('banner') || null
if (banner != null && banner instanceof File && banner.size > 0) {
await fileToBase64(banner)
.then((base64String) => {
if (base64String) {
formData.set('banner', base64String)
}
})
.catch((error) => {
console.error('Error converting file to base64:', error)
})
} else {
formData.delete('banner')
}
if (profile?.category?.length) {
formData.append('category', JSON.stringify(profile?.category))
}
Expand Down
38 changes: 38 additions & 0 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,41 @@ export const getTimeFormat = (duration: number) => {

return hours > 0 ? `${hours}:${minutes}:${secondsFormat}` : `${minutes}:${secondsFormat}`
}

export const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
const base64String = reader.result as string
const mimeType = file.type
const filename = file.name
const base64WithMetadata = `${base64String};name=${filename};type=${mimeType}`
resolve(base64WithMetadata)
}
reader.onerror = (error) => reject(error)
})
}

export const base64ToFile = (base64: string): File => {
// Extract MIME type and filename from base64 string
const mimeMatch = base64.match(/^data:(.*?);base64,/)
if (!mimeMatch || !mimeMatch[1]) {
throw new Error('MIME type could not be determined.')
}
const mimeType = mimeMatch[1]

const nameMatch = base64.match(/;name=([^;]*)/)
if (!nameMatch || !nameMatch[1]) {
throw new Error('Filename could not be determined.')
}
const filename = nameMatch[1]

const byteString = atob(base64.split(',')[1].split(';')[0])
const ab = new ArrayBuffer(byteString.length)
const ia = new Uint8Array(ab)
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i)
}
return new File([ab], filename, { type: mimeType })
}
36 changes: 23 additions & 13 deletions src/routes/[username]/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Actions, PageServerLoad } from './$types'
import { get, patch, putImage } from '$lib/api'
import { redirect, fail, error } from '@sveltejs/kit'
import { base64ToFile } from '$lib/utils'

export const load = (async ({ params, url }) => {
if (!params.username) error(404)
Expand Down Expand Up @@ -53,22 +54,31 @@ export const actions = {
addPropertyIfDefined(data, 'urls', newUser, true)

newUser.urls = newUser.urls.filter((i: string) => i)
const avatar = data.get('avatar') as File
const banner = data.get('banner') as File

if (data.get('avatar') !== null && avatar.size > 0) {
const urlLocation = await putImage(`user/current/avatar?bucketName=avatars`, avatar, {
userId: locals.user.userId,
token: locals.user.token
})
const avatar = data.get('avatar') as string
const banner = data.get('banner') as string
const convertedAvatar = avatar ? base64ToFile(avatar) : null
const convertedBanner = banner ? base64ToFile(banner) : null
if (convertedAvatar !== null && convertedAvatar.size > 0) {
const urlLocation = await putImage(
`user/current/avatar?bucketName=avatars`,
convertedAvatar,
{
userId: locals.user.userId,
token: locals.user.token
}
)
console.log(urlLocation)
}

if (data.get('banner') !== null && banner.size > 0) {
const urlLocation = await putImage(`user/current/banner?bucketName=banners`, banner, {
userId: locals.user.userId,
token: locals.user.token
})
if (convertedBanner !== null && convertedBanner.size > 0) {
const urlLocation = await putImage(
`user/current/banner?bucketName=banners`,
convertedBanner,
{
userId: locals.user.userId,
token: locals.user.token
}
)
console.log(urlLocation)
}

Expand Down

0 comments on commit 8beac24

Please sign in to comment.