2

i'm trying to upload image in Vue.js and send it to server with axios but there is some error i'm getting.

First of all:

I'm trying to send it like a formData. Not a base64 format.

here is my input:

<label>File
   <input type="file" id="file" ref="file" v-on:change="onChangeFileUpload()"/>
</label>
<button v-on:click="submitForm()">Upload</button>

and here is my data layer and methods:

export default {
  data() {
    return {
      file: ''
           }
       },
        methods: {
           submitForm(){
            let formData = new FormData();
            formData.append('file', this.file);

            this.axios.post('apiURL',
                formData,
                {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'token': '030303039jddjdj'
                }
              }
            ).then(function(data){
              console.log(data.data);
            })
            .catch(function(){
              console.log('FAILURE!!');
            });
      },

      onChangeFileUpload(){
        this.file = this.$refs.file.files[0];
      }
    }
    }

and i'm trying to show image before sending to server.

<img :src="file" /> 

but i can't display image

i'm getting error:

[object%20File]:1 GET http://localhost:3000/[object%20File] 404 (Not Found)

where i'm mistaken?

2 Answers 2

2

In order to show the image you can give url to src once the image is completely uploaded to server or if you want to show image before sending to server you have to encode your file in base64 format like this define base64 variable in data

    onChangeFileUpload ($event) {
      this.file = $event.files[0]
      this.encodeImage(this.file)
    },
    encodeImage (input) {
      if (input) {
        const reader = new FileReader()
        reader.onload = (e) => {
          this.base64Img = e.target.result
        }
        reader.readAsDataURL(input)
      }
    }

and then you can check if file is uploaded you should view image directly from url otherwise in base64

<img :src="base64Img" /> 
Sign up to request clarification or add additional context in comments.

Comments

2

Here is codepen of generating image.

https://codepen.io/Atinux/pen/qOvawK

Try this for file upload.

uploadFile(){
        let fd = new FormData();
        fd.append("file", this.file);

        this.axios.post('/uploadFile',fd,{
         headers: { 'Content-Type': undefined,
         'Authorization': `Bearer ${this.token}` },
        }).then(function (response) {
          if (response.data.ok) {
          }
        }.bind(this));

      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.