7
7
700Hp2022-02-07 11:40:30
JavaScript
700Hp, 2022-02-07 11:40:30

How to send a file to the server?

<form @submit.prevent="onSubmit" class="form" enctype="multipart/form-data">
      <input type="file" name="file" id="file" ref="file" @change="handleFileUpload">
      <button>
        Тест
      </button>
    </form>


setup() {
    const file = ref(null)

    const onSubmit = async () => {
      const formData = new FormData()
      formData.append('file', file.value[0])
      console.log(formData)
      await test(formData)
    }

    const handleFileUpload = () => {
      file.value = file.value.files
    }


    return {
      onSubmit,
      file,
      handleFileUpload
    }


const $authHost = axios.create({
  withCredentials: true,
  baseURL: process.env.VUE_APP_SERVER_URL,
})

export const test = async (file) => {
  const {data} = await $authHost.post('/documents/create', file, {
    headers: {
      'Content-type': 'multipart/form-data'
    }
  })
  return data
}


When a form is submitted, the formData object is always empty. Undefined comes to the server

Answer the question

In order to leave comments, you need to log in

1 answer(s)
7
700Hp, 2022-02-07
@700Hp

The answer is in the comments:
formData in the console will always be empty. It doesn't work quite as well as you might expect. Output not formData, but formData.get('file')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question