2

Context

I have a page with questions, this has an structure like the following

sections:[{
    section: 1,
    questions:[{
        question: 1,
        attachment: [FormData Object]
        ...
    },
    {
        question: 2,
        attachment: [FormData Object]
        ...
    }]
}, ...]

Each question have an attachment. What I did was to create a FormData object, upload the file into it and add it to the question object. Example:

let formData = new FormData();
formData.append('file', event.target.files[0])
question.attachment = formData

Everything's fine so far. The problem comes when I try to send it to the server. I doesn't pass the form object to it. This is the code I use to send it:

this.$http.post('my-path', {data: this.sections}, {headers: {'Content-Type': 'multipart/form-data'}, emulateJSON: true})

Using emulateJSON: true sends the data but attachment attribute is not contained in the request.

Using headers: {'Content-Type': 'multipart/form-data'} for some reason send a null request.

Is there a way to do something like that and actually works?

3 Answers3

3

I think the problem resides in serialization of form object.

I suggest you to encode each file in base64 and append it instead of form data object.

Or if you prefer posting form data included in JSON. Read about the correct way of form data serialization.

In my experience encoding files in base64 was the preferred way.

eWizard
  • 91
  • 2
0

you must set processdata to false

this.$http.post('my-path', {
    cache: false,
    processData: false,
    data: this.sections,
}, 
{
    headers: {
        'Content-Type': 'multipart/form-data'
    }, 
    emulateJSON: true
};)
Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
0

as @eWizard said. And he can use How to convert file to base64 in JavaScript??

I faced the problem with it but i solved it using async and await.

then in server he can convert it to file again.

and change the function to be like that:

   getBase64: function(file){
        var reader = new FileReader();
        return new Promise((resolve, reject) => {
            reader.onerror = () => {
                reader.abort();
                reject(new DOMException("Problem parsing input file."));
            };
            reader.onload = () => {
                resolve(reader.result);
            };
            reader.readAsDataURL(file);
        });
    }

and use it as the following

  var fileReaderPromise = await this.getBase64(image);