Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload image to server using axios

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.

like image 474
Rocky Avatar asked Mar 15 '18 12:03

Rocky


People also ask

How to upload selected file to server using Axios post method?

Consider you have a <Form /> component that contains an input element of type="file" and an upload file button, which uploads the selected file to the server using the Axios post method. First, you create a local React state selectedFile using useState () hook to store the currently selected file,

How to upload documents/images/videos in react using Axios?

In this tutorial, I will discuss how you can upload documents, images or videos in React using Axios Consider you have a <Form /> component that contains an input element of type="file" and an upload file button, which uploads the selected file to the server using the Axios post method.

How to add an image to an Axios request?

Yes you will have to set the content type in your axios request: axios.put (url, imageFile, { headers: { 'Content - Type ': imageFile. type } }); where imageFile is an HTML5 file object which should be an image in your case.

How do I send a POST request using Axios in Vue?

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.


Video Answer


2 Answers

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)
        })
    }
like image 122
DobleL Avatar answered Sep 27 '22 20:09

DobleL


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' }}
})
like image 31
bbsimonbb Avatar answered Sep 27 '22 22:09

bbsimonbb