Send the JSON file to the server by uploading it

Situation

Currently, I'm dealing with a page comprising questions structured as shown below:

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

Each question is associated with an attachment. To handle this, I've utilized a FormData object to upload the file and link it with the question object. For instance:

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

Everything seems to be in order at this stage. However, issues arise when attempting to send this data to the server. When utilizing the following code for sending it:

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

Despite using emulateJSON: true, the request is successful but the attachment attribute is not included in the request.

Moreover, specifying

headers: {'Content-Type': 'multipart/form-data'}
results in sending a null request for unknown reasons.

Is there a viable solution to effectively accomplish this task?

Answer №1

The issue seems to lie in the serialization of the form object.

My recommendation is to encode each file in base64 and add it instead of using the form data object.

Another option is to send the form data as part of a JSON payload. Make sure to research the proper method for serializing form data.

Based on my experience, encoding files in base64 has been the more effective approach.

Answer №2

Remember to disable processData for this request.

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

Answer №3

According to @eWizard's suggestion. Is it possible to utilize the guidance on How to turn a file into base64 in JavaScript??

I encountered an issue with this method, but I managed to resolve it using async and await.

Subsequently, he can revert the conversion on the server side.

Modify the function to resemble the snippet below:

   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);
        });
    }

Then implement it as shown below:

  var fileReaderPromise = await this.getBase64(image);

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

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...

Vue 3 presently does not support dynamically requiring "highcharts"

I've been working on integrating highcharts-vue into my project with the following code: import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import router from './router&a ...

Finding the index of a nested div element with a click event using jQuery

I'm currently working on a click event to retrieve the index of the outermost parent div, but I'm facing some difficulties in getting it to work. Here is a snippet showcasing a list of several divs: <div class="owl-item"> <div class= ...

Managing nested levels in Vue Draggable

Here is a link to the code sandbox: Nested Draggable Code Sandbox The nesting in this code is controlled through directives, specifically using v-if: <template> <draggable class="dragArea" tag="ul" :list="tasks" :g ...

What is the best way to keep my data within a global variable?

$(function(){ let spaceTravelersData; $.getJSON('http://api.open-notify.org/astros.json', retrieveData); function retrieveData(data) { spaceTravelersData = data; } alert(spaceTravelersData.people[0].name) }); I a ...

Discovering the managed metadata fields on a site page using REST API in SPFx Vue.js

Is there a way to retrieve Managed Metadata type values using API in SPFX with Vue.js? How can I access the actual values through the API /_api/web/lists/getbytitle('" + site page+"')/items? Having trouble fetching MMS fields? ...

How do I transfer a PDF received from a third-party to my client using a REST API on the backend?

After receiving a PDF from a third party, I stored the file on S3. Upon checking the file on S3, I was able to view the PDF without any issues. However, when sending the PDF to the client and verifying it using Postman, an empty PDF is displayed. Below is ...

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

Accessing QML Functions from JavaScript

Currently, I am faced with a challenge in my app development using Qt. I need to trigger a QML function from JavaScript when a specific event is triggered from my HTML page. I attempted the following method: app.html <html> <head><title& ...

Exploring GridJS Customization in VueJS

Currently, I am working on a project using Vue V.3 and incorporating Grid.JS for my tables. I have been trying to figure out if there is a way to customize the styling of the table elements within Grid (such as th, tr, etc). Despite referring to the offi ...

Utilizing Salesforce and DocuSign: A guide to automatically filling in the recipient of my envelope through DocuSign with the contacts from my records

In my Salesforce work, I'm currently customizing the Quote object. The default button labeled "Send with DocuSign" is already included on the Quote layout. My goal is to automatically populate the recipient of the DocuSign envelope with the contact(s) ...

Issues arise when JQuery functions fail to execute

This unique program showcases a series of error messages that are designed to appear under specific conditions. These conditions are identified through PHP code, following which the essential JQuery script is echoed via PHP to display the messages. Initia ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

Custom web addresses for files in the Vue 2.1 framework

After going through the documentation for Vue Router, it seemed like setting up redirects should be straightforward, but I'm having trouble making it work. My first attempt was to reference a file in S3: { path: '/rules', redirect: &ap ...

Rendering Koa without the need for a template engine

Currently, I am in the process of practicing my skills with Node.js and have made the decision to begin with Vue + Koa. Upon studying Vue, I have come to the realization that perhaps using a template engine is unnecessary. Instead, I can simply respond wi ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

JavaScript: Finding the current month and all subsequent months until the end of the year

Is there a way in vanilla JavaScript to retrieve the current month and the following 12 months? For instance, if today is April 2022, I would like the output to be: April 2022 May 2022 June 2022 July 2022 August 2022 September 2022 October 2022 November 2 ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

Navigate to a specific section on a different page while excluding a distance of X

I've implemented the script below to execute the action mentioned in the title. <script type="text/javascript"> var jump=function(e) { if (e){ e.preventDefault(); var target = $(this).a ...