dystcz / nuxt-sanctum-auth

Nuxt 3 + laravel sanctum authentication
134 stars 25 forks source link

upload multipart form data #29

Open noprobz09 opened 1 year ago

noprobz09 commented 1 year ago

Is there a sample of how to upload a file with multipart form data header? Thanks!

cvalues commented 1 year ago

same question..

const formData = new FormData();
          formData.append('image', data.image);
          formData.append('title', data.title);
          formData.append('body', data.body);

    $apiFetch(`api/url`, {
      method: 'POST',
      baseURL: config.public.API_BASE_URL,
      headers: {
        'Content-Type': "multipart/form-data"
      },
      params: formData

does not send the file

cvalues commented 1 year ago

encode file to base64 works, but only if filesize is under 30kb, why? FetchError: Failed to fetch

KarsjenKoop commented 1 year ago

You could try to cast the image to a blob data type. But I am not sure if it will work.

kreejzak commented 1 year ago

Hello everyone, you should be able to send multipart form data just like in ofetch that this module uses under the hood. I found one issue that mentions sending formData using ofetch here.

it mentions putting formData vartiable into Content-Disposition header.

const formData = new FormData()

formData.append('avatar', avatar)
formData.append('model', model)
formData.append('id', id)

$fetch('/avatar', {
  method: 'POST',
  body: formData,
  headers: { 'Content-Disposition': formData }
})

Please do let me know if this works. As I'm working on major release of this package and this totally should be topic mentioned in future documentation. Thanks

cvalues commented 1 year ago

yes, this works! thank you!

noprobz09 commented 1 year ago

Its not working this side. Below is my sample code

const file = event.target.files[0];
        const formData = new FormData()

        formData.append('file', file)

        $fetch($config.nuxtSanctumAuth.baseUrl + '/api/v1/attachments', {
            method: 'POST',
            body: formData,
            headers: { 'Content-Disposition': formData }
        })

The return status from the server is Status 419. Suggestions are much appreciated. Thanks!

kreejzak commented 1 year ago

Hello @noprobz09, in the example you have provided you are not using the $apiFetch method provided by this module. If you are trying to upload a file on the guarded route, you have to use $apiFetch instead of $fetch.

const { $apiFetch } = useNuxtApp()

//.... your code

const response = $apiFetch('/api/v1/attachments', {
    method: 'POST',
    body: formData,
    headers: { 'Content-Disposition': formData }
})

Please let me know if it helped. Thanks