Home > database >  How to post a file in Vue?
How to post a file in Vue?

Time:12-23

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

<template>
  <div >
    <div >
      <form enctype="multipart/form-data" @submit.prevent="createData">
        <div >
          <label for="title">Name</label>
          <input id="name" v-model="name" type="text"  />
        </div>
        <div >
          <label for="image">Image</label>
          <input ref="pic" type="file"  />
        </div>
        <div >
          <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>

CodePudding user response:

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 >

    <div >
      <form enctype=“multipart/form-data”>
        <div >
          <label for="title">Name</label>
          <input type="text"  name="name" id="myname">
        </div>
        <div >
          <label for="image">Image</label>
          <input type="file" name="pic" id="myfile" >
          <input type="hidden" id="studentId" name="studentId" value="">
        </div>
        <div >
          <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>
  • Related