Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: testing base64string conversion #1320

Merged
merged 2 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading