Skip to content
Advertisement

How to post a file in Vue?

How do I post a file in Vue? I am using Django. My response is ok.

<template>
  <div class="tasks_container">
    <div class="create_data">
      <form enctype="multipart/form-data" @submit.prevent="createData">
        <div class="form-group">
          <label for="title">Name</label>
          <input id="name" v-model="name" type="text" class="form-control" />
        </div>
        <div class="form-group">
          <label for="image">Image</label>
          <input ref="pic" type="file" class="form-control" />
        </div>
        <div class="form-group">
          <button type="submit">Create Data</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // student data
      students: [''],
      name: '',
      pic: '',
    }
  },
  methods: {
    async createData() {
      try {
        // Send a POST request to the API
        const response = await this.$http.post('http://localhost:8000/create/', {
          name: this.name,
          pic: this.pic,
          completed: false,
        })
        // Append the returned data to the tasks array
        this.students.push(response.data)
        // Reset the title and description field values.
        this.name = ''
        this.pic = ''
      } catch (error) {
        // Log the error
        console.log(error)
      }
    },
  },
}
</script>

Advertisement

Answer

I solved my problem:

my views.py

class Create(APIView):
    serializer_class = StudentSerializer
    def post(self, request):
        serializer = StudentSerializer(data=request.data,context={'request': request})  
        # print(request.data) // for client 
           
        if serializer.is_valid():
            serializer.save()
            # print(serializer.data) // for server
            data = {'result': 'success', 'message': 'Created Successfully'}
            return Response(data=data, status=201)
        elif not serializer.is_valid():
            data = { 'result': 'error', 'response':serializer.errors}
            return Response(data=data)

My .vue file

<template>
  <div class="tasks_container">

    <div class="create_data">
      <form enctype=“multipart/form-data”>
        <div class="form-group">
          <label for="title">Name</label>
          <input type="text" class="form-control" name="name" id="myname">
        </div>
        <div class="form-group">
          <label for="image">Image</label>
          <input type="file" name="pic" id="myfile" class="form-control">
          <input type="hidden" id="studentId" name="studentId" value="">
        </div>
        <div class="form-group">
          <button @click.prevent="createData" type="submit">Create Data</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script type="text/javascript">
export default {
  data () {
    return {
      // student data
      students: []
    }
  },
  methods: {
    async createData () {
      var formData = new FormData()
      var file = document.getElementById('myfile').files[0]
      var myname = document.getElementById('myname').value
      formData.append('pic', file)
      formData.append('name', myname)
      const headers = { 'Content-Type': 'multipart/form-data' }
      await this.$axios.post('http://localhost:8000/create/', formData, { headers }).then((res) => {
        this.students.push(res.data)
        console.log(res.data)

       

        // console.log(res.data.response.name[0])
        // console.log(res.data.response.pic[0])
      }).catch((error) => {
        // error.response.status Check status code
        console.log(error)
      })
    },
  },
 
}
</script>

<style scoped>
ul {
  list-style-type: none;
}
</style>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement