Ensure that the content-length header is properly set for each section of a multipart/form-data upload

I am looking to send a post request with multiple files using the multipart/form-data type. It's important for me to know the file size (content-length) of each file on the server side.

When constructing the POST request in Javascript, I utilize a FormData object and add File objects to it for upload. However, only a Content-type header and Content-Disposition header are added to each part, without a Content-length header, even though this information is available from the File objects themselves.

Is there a way to ensure that Content-length headers are set for every part within the FormData object when sending the request?

Below is the code snippet I am currently using, along with my workaround for the issue. While the code uses AngularJS for sending the request, the main concern lies in setting the Content-length headers.

var form = new window.FormData();

form.append('additional-field-1', new Blob(['some plain text'], {type : 'text/plain'}));

for (var file in fileList) {
    var fileObj = fileList[file];
    var count = 1 + parseInt(file, null);
    form.append('file-size-' + count, new Blob([fileObj.size], {type : 'text/plain'}));
    form.append('file-' + count, fileObj);
}

$http.post(url, form, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
}).success(.....

Answer №1

It seems like there might not be a direct way to add a custom header for each form data element. One alternative could be to include it in the content disposition header, specifically as part of the file name:

data = new FormData();
data.append('additional-field-1', new Blob(['some plain text'], {type : 'text/plain'}));

for (var i = 0; i< $( '#file' )[0].files.length; i++) {
   var fileObj = $( '#file' )[0].files[i];
   data.append( '{ size : ' + fileObj.size + ' }' , $( '#file' [0].files[i], $( '#file' )[0].files[i].name );
}

The server-side handling of this is not specified, but the request structure would resemble something like this:

------WebKitFormBoundarysZxMHYOzMkqDmOvR
Content-Disposition: form-data; name="additional-field-1"; filename="blob"
Content-Type: text/plain


------WebKitFormBoundarysZxMHYOzMkqDmOvR
Content-Disposition: form-data; name="{ size : 22984 }"; filename="MatrixArithmetic.vshost.exe"
Content-Type: application/x-msdownload


------WebKitFormBoundarysZxMHYOzMkqDmOvR
Content-Disposition: form-data; name="{ size : 187 }"; filename="MatrixArithmetic.vshost.exe.config"
Content-Type: application/xml


------WebKitFormBoundarysZxMHYOzMkqDmOvR--

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

Firebase: Database and Storage - the art of efficiently linking images to posts | Vue.js

React Redux MongoDB I have developed a platform for users to share text and an image with their posts. Currently, I am assigning the complete URL of the image associated with each post using post.postPicture. This method is functional. The images are sav ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Why isn't my Jquery click event able to download the csv file?

Initially, I was able to export a csv file using the html onclick element. However, when I switched to a jquery click event, the functionality stopped working. I don't understand why, as I believe the same function is being called. The Export.Expor ...

Creating a three-dimensional representation by projecting onto the surface of a sphere in ThreeJS

3D animation is a realm filled with numerous terms and concepts that are unfamiliar to me. I am particularly confused about the significance of "UV" in 3D rendering and the tools used for mapping pixels onto a mesh. I have an image captured by a 360-degre ...

Guide on downloading jsreport in .Net using C# without opening it

I am using JS Report to generate a file and save it in the root directory. However, I want the file to be downloaded directly instead of opening for viewing. var header = await _jsReportMVCService.RenderViewToStringAsync(HttpContext, RouteData, "H ...

Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing. I've implemented an intersection observer for lazy loading images, here's the code: const pictures = document.querySelectorAll("[data-src]"); function loadPicture(pic){ const src = p ...

Tips for correctly timing the loading of AngularJS and my models

Struggling to integrate Angular with my code, I have come to the conclusion that the issue must lie with me, considering how awesome Angular is. While some of my models contain only static data, most have dynamic data pulled from REST services or a combina ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

The "Go" button on iPhone triggers an error before the page is sent back

I am facing an issue with a web page that has a form containing multiple submit buttons with different functionalities like clearing the form, performing a calculation, or adding another entry line. The problem arises only on iPhone devices (tested on bot ...

Stuck on AMChart while trying to load data

Hello! I am currently utilizing the AMCharts framework to generate charts from data stored in a MySQL database. However, I have encountered an issue where instead of displaying the chart, I am stuck with a perpetual "Loading Data" message. You can view a ...

Update the property of every model within a Backbone collection

Using the pluck method, we can extract an array of attributes from each model in a Backbone collection. var idsInCollection = collection.pluck('id'); // returns ["id1","id2"...] I am curious to know if there is a method that can assign an attri ...

Using JavaScript to open a document file in Chrome at launch

Is it possible to automatically open a doc file stored on my C:// drive when a link is clicked on my HTML page? Here is the code I have been using: <a href="C://mytestfile.doc">Click Me To launch the DOC FILE</a> Unfortunately, instead of op ...

Special characters cause Ajax post to malfunction

My goal is to pass the content of a textarea to a PHP page for processing and storing in a SQL database. I need the textarea to handle special characters without any issues. However, when I input the following string into the textarea and submit it: J ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Issue arises as the backend code fails to successfully update the friends property array with the given id

Whenever the button labeled "Follow user" is clicked in the Frienddetail component, it triggers the addPeopleFollow function. The purpose of this function is to save the ID of the user being clicked (the user you are trying to follow) in the friends Array ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

Why is the refresh endpoint generating new tokens when an outdated refresh token is used?

Greetings! I am currently utilizing two npm libraries, namely bcrypt and jsonwebtoken. I have implemented an endpoint called /refresh-token wherein I aim to generate a new set of access and refresh tokens. The process involves sending the refresh token to ...

What are some ways to restrict dynamic form submissions?

$(document).ready(function(){ var i = 1; $('#add').click(function(){ if(i < 5){ i++; $('#dynamic_field').append('<tr id="row'+i+'"><td><div class="form-group">& ...

Extract source, medium, etc. data from __utmz GA with the help of JavaScript

Is it possible to retrieve the campaign, source, and medium that Google Analytics records all at once when the page loads? If so, could I use jQuery to look up the values from __utmz? ...

jquery autocomplete utilizing an external json data feed

I am facing an issue with my autocomplete function that was initially working with a local json source. I have decided to move it to an external json file, as my current code is lengthy (16k lines). However, I am struggling to make it work with the externa ...