Uploading an image using Vue.js

Currently, I am utilizing the ElementUi uploader and facing an issue where the file details are not being sent correctly to the back-end along with my form data:

Screenshots

When I select an image, here is the console log:

https://i.sstatic.net/StfNl.png

Here is the data that is sent to the back-end:

https://i.sstatic.net/MOuWb.png

Code

Photo input section in my code:

<el-upload
    action="#"
    :limit="1"
    :multiple="false"
    :on-change="photoChanged"
    :on-exceed="handleExceed"
    list-type="picture-card"
    :on-remove="handleRemove"
    :on-preview="handlePictureCardPreview"
    :before-remove="beforeRemove"
    :auto-upload="false">
    <i slot="default" class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>

Script section of my code:

export default {
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            form: {
                name: '',
                slug: '',
                price: '',
                new_price: '',
                sku: '',
                qty: 1,
                active: '',
                photo: '',
                shortDesc: '',
                longDesc: '',
                region: '',
                date1: '',
                date2: '',
                type: [],
                tags: [],
                brand_id: '',
                categories: [],
                resource: '',
                user_id: ''
            }
        }
    },
    methods: {
        onSubmit(e) { // Sending data to back-end
            e.preventDefault();
            axios.post('/api/admin/products/store', this.form)
            .then(res => {
                console.log(res);
            })
            .catch(error => {
                console.log(error);
            })
        },
        handleRemove(file) {
            this.form.photo = ''; // Removing photo from form when it's deleted
        },
        photoChanged(file, fileList){
            this.form.photo = file.raw;  // Adding selected photo to form
            console.log('file', file) // Screenshot 1
            console.log('raw', file.raw) // Screenshot 2
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleExceed(files, fileList) {
            this.$message.warning(`The limit is 1, you selected ${files.length} files this time, add up to ${files.length + fileList.length} totally, remove old image and try again.`);
        },
        beforeRemove(file) {
            return this.$confirm(`Cancel the transfer of ${ file.name } ?`);
        }
    },
  }
</script>

Any suggestions or solutions?

Answer №1

Encode your document in base64 format

Follow the code provided when choosing an image:

       handleImageSelection() {
          let selectedFile = this.form.picture

          if (selectedFile == '')
                return;

           this.convertToBase64(selectedFile);
       }

       convertToBase64(file) {
           let reader = new FileReader();
           let instance = this
           reader.onload = (e) => {
                instance.form.picture = e.target.files[0];      
           };
           reader.readAsDataURL(file);
       },

Connect the handleImageSelection function to your file input

Answer №2

I utilized FormData to transmit the photograph or document to the server. Explore JavaScript FormData here

  <form id="myForm" name="myForm">
    <div>
        <label for="username">Please enter your name:</label>
        <input type="text" id="username" name="username" v-model="imageData.name">
      </div>
     <div>
        <label for="useracc">Enter your account number:</label>
        <input type="text" id="useracc" name="useracc" v-model="imageData.account">
      </div>
    <label for="userfile">Select file to upload:</label>
    <input type="file" id="userfile" name="userfile">
  </div>
  <input type="submit" value="Submit!">
</form>

export default {
    data() {
        return { 
            imageData: {}
        }
    },
    methods: {
        uploadImageToServer() {
            // Step 1. Save the form Data and retrieve the new ID to save the image 
            axios.post('/api/admin/products/store', this.imageData)
            .then(res => {
                if(res.id) {
                //Step 2. Save the image to the retrieved ID
                let formData = new FormData();
                let file = document.getElementById('userfile');
                formData.append('file', file)
                axios.post('/api/admin/products/image/{id}', formData)
                    .then(res => {
                        console.log(res)
                    })
                }
            })
            .catch(err => {
                console.log(err)
            }) 

        }
    }
}

Here, Both form data & file data might not be transmitted in a single request. 1. Storing the form data first and receiving an ID. 2. Uploading the image data linked to the received ID. Remember to switch out the HTML with 'element-ui' syntax and ensure that your REST API accepts the form data as input.

Answer №3

Issue Resolved

After some consideration, I have decided to change my approach when sending data to the backend by first uploading the image separately with the action="#" attribute in my input field. This way, I receive the file name in my form and can simply send the file name along with the rest of the form data instead of the entire image file.

<el-upload
  action="/api/upload"
  :on-success="handleAvatarSuccess"
.....>


methods: {
  handleAvatarSuccess(res, file) {
    this.form.photo = res.data;
  },
}

By implementing this method, the file is sent to the backend immediately upon selection, and the stored file name is assigned to form.photo, which is then included with the other form inputs for submission.

I believe this solution could be beneficial for others facing similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using NodeJS to handle server side FormData

Currently, in the process of building a web application with nodejs on the server-side, I am facing a challenge of transferring PDF files from the client to the server. Client side: var files = new FormData(); var count = 0; $('#tableSlideId tr&apos ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Do you know if there is a setting in prettier that allows line breaks to be preserved?

Encountering an issue with the prettier extension in VS Code, Whenever I enter the following code: const result = await pool .request() .query('select NumberPlate, ID, TimeStamp from RESULTS order by ID'); and save the file, it con ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Eliminate elements from an array within a promise

I am facing an issue with the currentBillCyclePath parameter in the following function. I need to use this parameter to filter out certain elements after executing the query. However, inside the while loop, the value of currentBillCyclePath is undefined. ...

Utilize Element UI autocomplete to transfer data into a VueJS-powered table's input fields

I am currently working on designing an invoice form using the Element UI framework. I have successfully integrated an autocomplete feature that retrieves data from the loadAll array. Upon clicking the add button and selecting an item_name from the autocomp ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

Develop a search feature that automatically filters out special characters when searching through a

I am currently developing a Vue-Vuetify application with a PHP backend. I have a list of contacts that include first names, last names, and other details that are not relevant at the moment. My main query is how to search through this list while disregardi ...

Preserving input data based on click and change events

Upon form submission, I encounter an issue with displaying only the divs that contain fields with saved values. The form saves user-entered values using PHP, where some of the fields are initially hidden within div elements until an onclick or onchange eve ...

Guide on using webpack to import jQuery

When using webpack, is it necessary to install the jquery file from npm, or can I simply require the downloaded file from the jquery website? directory app/ ./assets/javascripts/article/create/base.js ./assets/javascripts/lib/jquery-1.11.1.min.js webpack ...

Reliable selection menu for changing fields

Can someone help me with this coding issue? I am attempting to create a dependent dropdown menu where selecting a category will also display relevant equipment. However, in my current setup, only the category field is functioning properly. When I try to a ...

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

What is the best way to implement a click event on the v-data-table component?

I am facing an issue where the editItem function is not being called when I click on a table row. The current behavior is that clicking on the row does not display the details page, but if I put the click event on a specific table data cell, the editItem f ...

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

The Material UI library is signaling that there is an unidentified property called `selectable` being used with the <table> tag

Whenever I try to add the selectable attribute to the Table component in Material-UI using React JS, I encounter an error. Despite checking that selectable is indeed included in TableProps, the issue persists. List of Dependencies : "material-ui": "1.0.0 ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Tips for incorporating HTML code within a select option value?

I am working with AngularJS to create a Visual Composer for a website. One feature I want to incorporate is the ability to add HTML code based on the selection made in a dropdown menu. However, I am struggling to figure out how to include the HTML within t ...