nw.js sending a multipart/form-data request

I am looking to send POST data to a server from nw.js. The data consists of simple name-value pairs and one file, meaning that the request type will be multipart/form-data. All the data needs to be sent in one single request.

To do this, I have been using XMLHttpRequest and FormData to send my data. Here is the code snippet:


function toArrayBuffer(buffer) {
    var ab = new ArrayBuffer(buffer.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        view[i] = buffer[i];
     }
     return ab;
}

var fData = new global.window.FormData();
fData.append('email', email);
fData.append('foo', 'bar');

var fs = require('fs');
var buff;

fs.readFile(data.path, function(err, data) {
    if (err) {
        console.log('file reading error');
        // handling errors
    } else {
        console.log('reading complete');
        buff = data;
        send();
    };
});

function send() {
    var blob = new global.window.Blob([toArrayBuffer(buff)], {type: 'image/jpeg'});
    fData.append('file', blob);

    var xhr = new global.window.XMLHttpRequest();
    xhr.open("POST", url);
    xhr.timeout = 30000;
    xhr.onload = xhr.onerror = function() {
        // handling result or errors...
    };
    xhr.send(fData);
}

However, I noticed that the XMLHttpRequest sends all data except for the file. The request payload is shown below:


------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="email"

email
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="message_id"

4b38ad18-0501-9c0d-9cf6-e0a2fcca1898
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="foo"

bar
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: image/jpeg


------WebKitFormBoundaryc0ClIBTxPlqPmilD--

The file section appears to be empty in the request payload.

I also tried passing the Buffer directly to FormData. In this scenario, the file does get sent but the server interprets it as a string instead of a file (common issue with PHP servers).

Thank you.

Answer №1

To tackle this issue, I utilized the form-data library:

const FormData = require('form-data');
const form = new FormData();
const fs = require('fs');
form.append( 'email', userEmail );
form.append( 'foo', 'bar' );
form.append('image', fs.createReadStream(imageFile)); // attach image file
form.submit(uploadUrl, function(error, response) { ... }

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

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Updating password in Django with AJAX

During the development of my website, I successfully added the functionality for users to change their passwords. This was achieved by utilizing the pre-existing view in django.contrib.auth. However, the next step is to enhance this feature by implementin ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Dealing with ajax requests when there is no network connection and the wifi is turned off on an Android

Currently, I am in the process of creating an Android Application with phonegap. While everything is functioning correctly with the request/response handling, I am encountering a challenge when there is no 3G network available and WiFi is disabled. In this ...

Add a fresh widget to the DOJO attachment point without overwriting

Here is some code I have: postCreate: function() { this.items.forEach(lang.hitch(this, function(item) { new SideNavigationItem({ name: item.name }, this.container); })); } This code snippet ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

Create an animated effect using JavaScript to toggle the classList

As I delved into the world of CSS and HTML, I stumbled upon an interesting tutorial for creating a responsive navbar. You can check it out here. The tutorial showcases the mobile version of the navbar using the javascript function classList.toggle. I was ...

Hiding elements in HTML with React when data is null

Is there a way to hide elements using classes like "d-none" when the data is null in React? <span className="product__tag">{prod.tag1}</span> <span className="product__tag">{prod.tag2}</span> <span classN ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

Creating a personalized class in Google Apps Script: a step-by-step guide

I'm trying to define a new class within my Google Apps Script. Even though the language is based on JavaScript, I encountered an issue while using an example from a JavaScript manual: class Polygon { constructor(height, width) { this.height = ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

Unable to prevent ordered lists from overlapping with other content I attempt to place beneath them in HTML

function filterImages() { let input = document.getElementById('searchbar').value; input = input.toLowerCase(); let images = document.getElementsByClassName('gallery'); for (let i = 0; i < images.length; i++) { ...

Transferring user inputs to the server through jQuery-AJAX

I've encountered some issues when trying to send form data inputs to the server. Despite alerting each form input, I keep getting empty alerts. Here's my code snippet: With my current code, it only alerts 0. However, posting normally seems to wor ...

What is the process for bringing an array from a .js file into an HTML document?

Exploring the world of JS and HTML, I recently came across an assignment that involved working with a file named stocks.js, which houses an array of stock information: 'use strict'; const stocks = [ { company: 'Splunk', symbol: &ap ...

Verify if an Ajax request has been made

I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the Acti ...

Tips for adjusting the class of elements in neighboring rows of an HTML table with the help of jQuery's nextAll() selector

While attempting to switch classes using the jQuery selector .nextAll(':lt(3)'), I encountered an issue. The class change does not take effect on new rows of HTML tables. It seems like the class change for the next 3 cells is only being applied ...

Guide on how to compare two arrays in JavaScript and identify mismatches by their respective indices

let x=["e","f","g","h"]; let y=["f","e","g","h"]; I want the following result: Inconsistent array from x Inconsistency array=["e", "f"]; ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

Spinning jQuery Ajax Loader

Currently, I have implemented the following jQuery/Ajax script to load comments when a user clicks on a div: function showComments(post_id) { $("#comment-"+post_id).toggle(); $.ajax({ dataType: 'html', cache: false, ...