core icon indicating copy to clipboard operation
core copied to clipboard

[Blob] `handleUpload(event)` and `useUpload(path)`

Open atinux opened this issue 1 year ago • 2 comments

On the servers-side:

// api/upload.post.ts
export default eventHandler(event => {
  // Do auth checks...
  return hubBlob().handleUpload(event, {
    formKey: 'file', // default
    multiple: true | false, // throw error if multiple files & false, default true
    // ... put() options
    // ensureBlob() options
  })
})

We should add a prefix option to put() to we can also have it in handleUpload(event)

On the app side:

<script setup>
async function upload(e: Event) {
  const { pathname } = await useUpload('/api/upload')(e.target.image)
}
</script>

<template>
  <div>
    <h3>Images</h3>
    <form @submit.prevent="upload">
      <label>Upload an image: <input type="file" name="image"></label>
      <button type="submit">
        Upload
      </button>
    </form>
</template>

atinux avatar Apr 25 '24 14:04 atinux

I was just working on a way to preview the image before you upload it. Maybe you can add this to the useUpload composable? Or is the pathname the location of the local image which can then be used in a <img> element?

Gerbuuun avatar Apr 25 '24 16:04 Gerbuuun

You can use URL.createObjectURL(file) in the Vue part to display the blob:

<script setup lang="ts">
const avatar = ref()

function onFileChange (files: FileList | null) {
  if (!files?.length) return
  avatar.value = URL.createObjectURL(files[0])
}
</script>

<template>
  <form class="p-2">
    <UFormGroup name="avatar" label="Avatar" help="JPG or PNG, 1MB max.">
      <UAvatar :src="avatar" alt="avatar" size="lg" />
      <UInput ref="fileRef" type="file" accept=".jpg, .jpeg, .png" @change="onFileChange" />
    </UFormGroup>
  </form>
</template>

See a demo on https://stackblitz.com/~/edit/github-x6x77g

atinux avatar Apr 26 '24 11:04 atinux