How to upload a multipart form with JSON and file using Dojo's XHR functionality

I've been struggling to find a solution for this issue. The closest I found was a thread on Stack Overflow about composing multipart/form-data with different Content-Types, but it didn't fully address my problem.

Here's the situation - I have a .NET webservice that requires a POST request with both JSON data (such as title and content) and files uploaded by the user. I'm sending this request from a DOJO Dialog box using an AJAX post request.

The challenge is to use 'multipart/form-data' while gathering data from multiple sources beyond just form elements. My code snippet looks something like this:

var values = { // created JS object with data from various sources };
var formData = new FormData();

formData.append('data', json.stringify(values));   
var files = document.getElementById("files").files;
var file = files[0];
formData.append("file0", file);

xhr.post('link_to_my_service',  
{ 
    handleAs: "json",
    sync: false,
    data: formData,
    headers: {                     
         'X-Requested-With': '',
         'Content-Type': false,   
         'Accept': 'application/javascript, application/json'
    }
})

The request reaches the server successfully, however, the issue arises due to the lack of a 'Content-Type' set in the 'data' part of the request. This has proven difficult to resolve. One suggestion involved creating a BLOB and passing the JSON string through it, but this solution wasn't effective either.

I'm currently at a standstill and unsure how to proceed given that modifying the service isn’t an option. Any insights on how to work around this limitation within Dojo 1.10 would be greatly appreciated.

Answer №1

Perhaps arriving a bit later, but timeliness is of no concern.

The link you identified as most relevant to your issue actually provides a solution (Last answer from Yeo).

In light of that response, I suggest constructing the FormData object in the following manner:

let formData = new FormData();

// include the file in your form data.
formData.append('file', file);    

// create an object-like structure within your form data.
for (let key in values) {
  if(values.hasOwnProperty(key)) {
    formData.append(`data[${key}]`, values[key]);
  }
}

// configure your post request options.
...

let handle = xhr.post(url, options);

Then, on the server side, you can transform this back into an object by iterating through the request's body parts and gathering the necessary fields.

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

Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using ...

Sharing resources between different origins and the file:// protocol

I have been developing an HTML5 application that is collecting data from various sources using JSONP. So far, everything involving a GET request has been functioning perfectly. However, I have encountered a hurdle while attempting to make a POST request. T ...

When a user presses on an item in the FlatList component, a page will display with unique

I am working on an endusers page where I retrieve data from an API and display the results in a flatlist as list items. My goal is to have a single dynamic page for each user that shows their information, without creating a separate file for each user. Th ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

What are the steps to retrieve the JSON response from Rally REST API using either JSONP or an HTTP Proxy?

Greetings fellow Stackoverflow members! This is my initial post on this platform, after years of being a regular visitor. Our in-house defect tracking application relies on ASP. Currently, we follow a manual process to transfer all necessary Rally User st ...

Reading cached JSON value in a Node.js application

Recently, I embarked on creating a node.js application and reached a stage where I needed to retrieve a value from an updated JSON file. However, my attempts using the 'sleep' module to introduce a small delay were unsuccessful. I'm relativ ...

RestKit JSON Object Mapping: A powerful tool for converting JSON objects

Below is a JSON response that I have received. How can I perform object mapping for this data? My platform of choice is iOS and I am utilizing RestKit. { "predictions":[ { "description":"User1", "id":"75b8c57b4443f4b ...

What is the best way to convert objects of a class into a list by utilizing a JSON file?

Currently in the process of developing a murder mystery game similar to Cluedo, I am modifying the playerpiece class. As part of this project, I have created a json file named data.json to store various details about the playerpieces such as Character Name ...

Difficulty with NodeJS, Hapi, and Cascading Style Sheets

I've decided to challenge myself by creating a small webhost using Node.js with hapi. Even though I'm not an expert in Node.js, I am eager to learn as much as possible. Currently, my main issue revolves around fetching a CSS file from an include ...

Rails AJAX Voting Functionality Implementation Bug

I'm currently working on a social app where I have successfully implemented the Acts As Votable gem. However, I am facing an issue with getting it to work via ajax in order to prevent page refreshes that disrupt the user's browsing experience. U ...

Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using: uploadFile() { let vm = this; var file = vm.$refs["testeLogo"].files[0]; var reade ...

Tips for effectively utilizing the select feature with Firebase data within the Angular UI typeahead functionality

I am currently attempting to integrate Angular-UI typeahead with data retrieved from my Firebase database. The structure of the data is as follows: Data:{ "-JL8IPEAs0vLSt4DJ4V9": { "name": "Something" }, "-JL8IbggYn3O8jkWoPmv": { "name": "Something Els ...

"Tips for stopping users from using Ctrl+U to view page source in

Is there a way to prevent users from viewing the source code (HTML + JavaScript) of a page by disabling Ctrl+U in the browser? ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

Within Blade, Laravel and Vue components are able to communicate by sharing data from one component to another

Is it possible to achieve this task? Here is the scenario: I have a left navbar displaying membership status (active/inactive). Once the payment gateway receives the payment, a webhook is triggered via Paddle(Laravel Paddle API). During the webhook proc ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Tips for preventing the unmounting of child components while utilizing JSX's map function

This is a condensed version of a question I previously asked. Hopefully, it's clearer and more comprehensible. Here is a simple application with 3 input fields that accept numbers (disregard the ability to enter non-numbers). The app calculates the s ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

AngularJS and the JavaScript programming language

Struggling with opening an Excel sheet by clicking on a button? I've written the code, but encountering issues. function openFile(strFilePath) { var objExcel; //Create EXCEL object objExcel = new ActiveXObject("Excel.Applicati ...

Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component : <script> export default{ props:['search','category','shop'], ... methods: { getVueItems: function(page) { this.$store.disp ...