How can I upload image to server using axios

21,935

Solution 1

A standard (mostly) approach will be to split the logic in two, if you want to save the image path on your product, you firstly need to upload the photo to the server and return their path.

pseudo example:

component's data

    {
      imagePath: '',
      productSpect: ''
    }
``

``html

<input type="text" v-model="productSpect" />
<input type="file" @change="uploadImage" name="image" id="image"  accept="image/*" >
<button type="submit" @click.prevent="submit"> Submit</button>`

``

**uploadImage method**

    uploadImage (e) {
      let img = e.target.files[0]
      let fd= new FormData()
    
      fd.append('image', img)
    
      axios.post('/upload-image', fd)
        .then(resp => {
           this.imagePath = resp.data.path
        })
    }


**submit method**

    submit () {
      let data = {
        imagePath: this.imagePath,
        productSpect: this.productSpect
      }
    
      axios.post('/path/to/save', data)
    }



**edited method to handle just only 1 image on the server**

Change the input `@change` to just save the img on a property under data():

    <input type="file" @change="image = e.target.file[0]" name="image" id="image"  accept="image/*" >

    submit() {
      let fd= new FormData()
    
      fd.append('image', this.image)
    
      axios.post('/upload-image', fd)
        .then(resp => {
           this.imagePath = resp.data.path
    
           let data = {
             imagePath: this.imagePath,
             productSpect: this.productSpect
           }
        
           axios.post('/path/to/save', data)
        })
    }

Solution 2

There is nothing specific to Vue in this question. To send a POST request with axios, the easiest thing to do is to grab the formData of the html form and pass it as the data argument to Axios. To do this in Vue, just give your form tag a ref, then create a formData from the form.

<form ref="myForm">

// then in your method...
var myFormData = new FormData(this.$refs.myForm)
axios({
    method: 'post',
    url: 'myurl',
    data: myFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
})

Solution 3

for upload file I've used vuetify https://vuetifyjs.com/en/components/file-inputs/

 <v-file-input
   accept="image/png, image/jpeg, image/bmp"
   placeholder="Pick an avatar"
   prepend-icon="mdi-camera"
   v-model="imageData"
  ></v-file-input>
 <v-btn color="primary" @click="onUpload">Upload</v-btn>

in my vue method I have

onUpload() {      
    let formData = new FormData();
    formData.append('file', this.imageData);
    axios.post(
        "/images/v1/upload"
        ,formData
        ,{headers: {"Content-Type": "multipart/form-data"}}
    )
    .then(response => {
      //...
    })
    .catch(e => {
       //...
    })
}

Best regards!

Share:
21,935
Rocky
Author by

Rocky

Updated on July 09, 2022

Comments

  • Rocky
    Rocky almost 2 years

    I am trying to send a form along with an image. Note: I don't want to save the image in a database, I want to save it in a folder which I created on the server and just add a link of the image to the database.

    From the server side I know how to handle this, but I don't know how to do this from font-end. With other words, how can I send the image using axios to the server.

    <template>
        <input type="text" class="form-control" id="specdesc" v-model="product.specdesc" name="specdesc" placeholder="Enter your name">
        <input type="file"  name="image" id="image"  accept="image/*" >
        <button type="submit" class="btn btn-sm btn-primary"@click.prevent="Submit()"> Submit</button>
    </template>
    
    <script>
    export default {
       name: 'Addproduct',
       data(){
            return{
                image: '',
                product:{
                    specdesc:'',
                },
            }
        },
        methods:{ 
          Submit(){
            var _this=this
    
            //  console.log(this.image)
            console.log(this.selectedCategory.category_name)
            var product = {
                specification:this.product.specdesc,
                imagename:this.image
            }
              
            this.$http.post('http://localhost:3000/api/companyproducts',product) 
            .then(function (response) {
                console.log(response.data);
            })
            .catch(function (error) {
                console.log("error.response");
            });
            }
        },
    }
    </script>
    

    Now my question is how can I upload a image as well as the input name using axios. Moreover I want to use the same method i.e var product to send.

  • Rocky
    Rocky about 6 years
    but what happen if he/she upload 3 image sequentially i.e suppose user submit 3 images one after another that means 3 image created on my server side folder now when user finally submit there form they have 3 image that means only one image belongs to product and other are useless image how I can prevent that
  • DobleL
    DobleL about 6 years
    then on the uploadImage method just save it in one var, and when the user hit submit, first save it in the server and then apply the submit logic, or implement some cleaner on the backend, like remove all images where their path is not used on a product
  • Em Ji Madhu
    Em Ji Madhu about 6 years
    i think one more approach would be, disable inputs after user selected one file and let them submit that and then proceed with another upload. here is the example github.com/emjimadhu/vuetifyjs-upload