Skip to content

Commit 1f85aba

Browse files
committed
chore: upload file to storage
1 parent 8da732a commit 1f85aba

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

pages/storage.vue

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ async function addFile () {
1919
loading.value = true
2020
2121
try {
22+
const formData = new FormData()
23+
formData.append('data', new Blob([JSON.stringify({ key })], {type: 'application/json'}))
24+
formData.append('file', newFileValue.value)
2225
const file = await $fetch('/api/storage', {
2326
method: 'PUT',
24-
body: {
25-
key,
26-
value
27-
}
27+
body: formData
2828
})
2929
const fileIndex = storage.value.findIndex(e => e.key === file.key)
3030
if (fileIndex !== -1) {

server/api/storage/index.put.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import type { MultiPartData } from 'h3'
2+
3+
export default eventHandler(async (event) => {
4+
await requireUserSession(event)
5+
6+
const form: MultiPartData[] = await readMultipartFormData(event)
7+
const dataPart = form.find((part) => part.name === 'data')
8+
const filePart = form.find((part) => part.name === 'file')
9+
if (!dataPart || !filePart) {
10+
throw createError(`Missing ${!dataPart ? 'data' : 'file'} body param.`)
11+
}
12+
13+
try {
14+
const data = JSON.parse(dataPart.data)
15+
const file = filePart.data.toString()
16+
17+
// Set entry for the current user
18+
19+
const res = await useBucket().put(data.key, file, {
20+
customMetadata: {
21+
filename: filePart.filename!,
22+
type: filePart.type!
23+
}
24+
})
25+
return res
26+
} catch (e: any) {
27+
throw createError({
28+
statusCode: 500,
29+
message: `Storage error: ${e.message}`
30+
})
31+
}
32+
})

0 commit comments

Comments
 (0)