Search code examples
javascriptlaravelvue.jsaxiosform-data

formData vs JSON when uploading images (best practices)


JSON seems to have a lot of benefits over formData for sending data to server. Some of them include sending nested data without having to manually stringfy, or making possible a simple code like below to work:

data() {
    return {
      form: {},
    }
  },
methods: {
    submit() {
      this.form = await this.$axios.$post('/images', this.form)
    },

No matter how 'form' object is structured, i could easily send it and manage the JSON in the server. The problem with this approach seems to arrive when we need to send some uploaded files together. The most common approach seems to be sending the files as base64, but this is a bad practice since it makes file sizes bigger. Is there anyway so we can send a file appended to this JSON body without converting it to base64 or the only way would be to use formData method? Something like multipart-formdata but with JSON?


Solution

  • No, the json content-type cant have a file appended to it. For APIs its better to separately do a file upload, then use the path to the file (or the disk and file name) for relating the resource to the file.

    If you have to do a single request then it must be in "formData" form.

    Update : Another way is to encode the file in base64 format from the client, then decode it in the back-end (potential quality loss, have not tried this, just a suggestion)