switchon@lavalamp.biz
+27(0) 83 419 4851 / +27(0) 21 036 1165
Application & software development
Get A Quote

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact
    switch branding in your angular project
    Switch Branding In Your Angular Project
    Feb 7, 2022
    buddy coding
    Buddy Coding And Talking It Through
    Feb 16, 2022

    Simple Way To Send A File With Auxiliary Data Via Axios In VueJS

    Categories
    • Software Development
    • Web Development
    Tags
    • api
    • auxiliary data
    • axios
    • backend
    • base64
    • embed
    • encode
    • file
    • file transfer
    • file upload
    • frontend
    • html
    • software development
    • vue
    • web development
    sending files with auxiliary data
    sending files with auxiliary data

     

    Many times in the past I’ve spent countless hours trying to figure out how to send an image or a text file to my backend with other data such as a custom name, a description or caption. Every time the common answer that pops up is to use a package like FS to achieve this however, not all frameworks allow Access to such packages, VueJS being one of the few frameworks that don’t allow access to the File System module.

    So here is a simple solution that might work for you if you’re sitting with the same issue.

    Lets create a simple component on our front-end in view called AddFile.vue

    <template>
    <div>
           <input type="file" @change="fileChange" placeholder="Select File to upload…"/>
           <input type="text" v-model="fileName" placeholder="Custom filename…"/>
           <input type="textarea" v-model="fileDesc" rows="4” placeholder="Custom filename…"/>
           <embed  name="plugin" :src="preview" type="application/pdf">
           <button @click="submitFile">Submit</button>
    </div>
    </template>
    <script>
    export default {
           data(){
                  return{
                         selectedFile:null,
                         description:null,
                         fileName:null,
                         preview:null,
                  }
           },
           methods:{
                  fileChange(event){},
                  async submitFile(){},
           }
    }
    </script>

    As you can see we have:

    • an input field for the file type,
    • A field to customise the filename once we submit
    • A text area for the additional file description
    • an embed field in order to view a preview of the file that has been selected
    • and the submit button

     

    fileChange function

    In your component’s methods we’ll add the following code inside the fileChange function to store the file into the selectedFile variable.

    var files = event.target.files || event.dataTransfer.files;
    if (!files.length)
           return;
    this.selectedFile = files[0];

    We can then retrieve the filename from the selectedFile variable as well as the preview data within the same fileChange function.

    this.fileName = this.selectedFile.name;
    this.preview = URL.createObjectURL(this.selectedFile)

    Now that we have the file data, all that needs to be done is converting it to a format that can be sent over axios.

    async toBase64(file) {
           return await new Promise((resolve, reject) => {
                  const reader = new FileReader();
                  reader.readAsDataURL(file);
                  reader.onload = () => resolve(reader.result);
                  reader.onerror = error => reject(error);
           });
    },

    We can start by adding this toBase64 function to our component’s methods

    This returns the data that was in the file as a base64 string that we can then send via axios as a regular string in a JSON object.

     

    submitFile

    In the submitFile function that will be triggered by the Submit button,we add the following line of code:

    let file = await this.toBase64(this.selectedFile);

    This will call send the file to the function we wrote previously and that’s left to be done in the submitFile function is to send the data via axios to whichever endpoint needs it.

    let postData={
           fileData:file,
           fileName:this.fileName,
           description:this.description
    };
    axios.post(`${url}`, postData, {headers:{'Content-Type':'application/x-www-form-urlencoded'}})

    From here onwards we can decode the data on the backend again or on the front-end using the following snippet of code:

    async dataURLtoFile(dataurl, filename) {
           return await new Promise((resolve, reject) => {
                  try{
                         var arr = dataurl.split(','),
                         mime = arr[0].match(/:(.*?);/)[1],
                         bstr = atob(arr[1]),
                         n = bstr.length,
                         u8arr = new Uint8Array(n);                   
                         while(n--){
                               u8arr[n] = bstr.charCodeAt(n);
                         }
                         resolve( new File([u8arr], filename, {type:mime}))
                  }catch(e){
                         reject(e);
                  }
           })
    },

    This will create a file using the file data that we sent through all that needs to be done is the file and fileName parameters need to be passed to the dataurl and filename parameters of the function respectively.

     

    Contact us


      Related posts:

      dynamic doughnut graph using laravel vue componentDynamic Doughnut Graph Using Laravel Vue Component laravel livewireLaravel Livewire how to send a tweet from within your angular app via node jsHow To Send A Tweet From Within Your Angular App Via Node Js how to deploy your app/website on herokuHow To Deploy Your App/Website On Heroku
      Share
      4
      Abduraghmaan Gabriels
      Abduraghmaan Gabriels
      Abduraghmaan is a young up-and-coming full-stack software engineer. He started his journey in the world of tech by modifying the small scripts in old Pokemon games and ended up falling in love with coding. His ultimate passion is bringing new people into the world of technology and teaching them the wonders of Software development.

      Leave a Reply Cancel reply

      Your email address will not be published. Required fields are marked *

      Lava Lamp Lab


      Like technology, a lava lamp constantly changes form, producing new conditions with every passing moment



      lava lamp lab facebook   lava lamp lab twitter   lava lamp lab linkedin   lava lamp lab instgram

      Services


      Application & software development

      Outsourced software development

      Project based resourcing

      Digital marketing & consulting

      Graphic design & consulting

      UI / UX design & consulting

      Contact Us


      +27(0) 83 419 4851

      +27(0) 21 036 1165


      switchon@lavalamp.biz


      Unit 4 Monaco Square,
      14 Church Street,
      Durbanville,
      Cape Town, 7550

      NBConsult Group


      nbconsult
      nbconnect msp
      nbclearning
      river broadband
      designer needed
      © 2023 Lava Lamp Lab (Pty) Ltd | All Rights Reserved | Privacy Policy
      Contact us now

        Application & software development

          Outsourced software development

            Project based resourcing

              Digital marketing & consulting

                Graphic design & consulting

                  UI/UX design & consulting

                    Lease an expert

                      Recruitment services

                        We are using cookies to give you the best experience on our website.

                        You can find out more about which cookies we are using or switch them off in settings.

                        Lava Lamp Lab
                        Powered by  GDPR Cookie Compliance
                        Privacy Overview

                        This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

                        Strictly Necessary Cookies

                        Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

                        If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

                        3rd Party Cookies

                        This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

                        Keeping this cookie enabled helps us to improve our website.

                        Please enable Strictly Necessary Cookies first so that we can save your preferences!

                        Cookie Policy

                        More information about our Cookie Policy