Send data through a file using the file=@ format with the help of Javascript

My current challenge involves making an api call that necessitates uploading a file in the file=@ format. The api call works perfectly using postman/curl. Here is an example:

curl -X POST \
    'http://localhost/test' \
    -H 'Authorization: Bearer ...' \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
    -F 'file=@C:\Users\aaa\Downloads\testdata.xlsx'

However, when attempting to perform this action on the web, I receive a 400 error from the API. I have tried various approaches, and below is my current attempt:

<form id="test-form">
    <input id="file-import" type="file" name="file">
    <div id="test">upload file</div>
</form>


<script>

jQuery(document).on('click', '#test', function (e) {
    var data = new FormData();
    data.append("file", jQuery('#file-import')[0].value);

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost/test");
    xhr.setRequestHeader("Authorization", "Bearer " + sessionStorage.t);
    xhr.setRequestHeader("Content-Type", "multipart/form-data;         boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

    xhr.send(data);
});
</script>

When I try to convert the frontend code into the file=@ format using devtools, I get the following:

curl "http://localhost/test" 
-H "Authorization: Bearer ..." 
-H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" 
--data-binary ^"------WebKitFormBoundaryW0inUk99iHMiw7fd^

Content-Disposition: form-data; name=^\^"file^\^"^

^

C:^\^\fakepath^\^\testdata.xlsx^

------WebKitFormBoundaryW0inUk99iHMiw7fd--^

^" --compressed

How can I modify my frontend code to adhere to the file=@ format instead of the current approach? Alternatively, is there a different method I should consider?

Please let me know if additional information is needed to assist in resolving this issue.

Answer №1

The reason behind this problem was due to the presence of a content-type header in the request. By removing this, the browser was able to automatically set a default content-type, allowing me to successfully upload a file through the web.

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

AngularJS encountered an error while attempting to load a template: [$compile:tpload]

After developing my angularjs example app in my netbeans ide based local server, I encountered an issue when I tried to move the application to an nginx server. The browser displayed the following error message: Error: [$compile:tpload] Failed to load tem ...

Issue: spawn command UNKNOWN while running npx create-react-app

Encountering an error message in the command prompt while trying to create a React app. Here are some details: Node version: v16.16.0 Npm version: 8.15.1 Operating system: Windows 11 Attempted solutions include running the command in PowerShell, cleari ...

Which method is better for HTML5/JavaScript GeoLocation: Passing data to a callback function or suspending an async call using promises?

Trying to figure out how to utilize HTML5/Javascript Geolocations effectively for passing location data to an ajax call and storing it in a database. The main challenges I'm facing are the asynchronous nature of the Geolocation call and issues with va ...

retrieve JSON response from struts2 controller

My web application utilizes jquery and struts2. I am now facing the task of embedding a Google map into my webpage and adding some markers to it. To accomplish this, I have used the jquery.getJSON() command to send a request to a struts2 action. Here is a ...

Preventing default events and continuing with jQuery

Currently, I am working on a Django project and have integrated the Django admin along with jQuery to insert a modal dialog between the submission button and the actual form submission process. To accomplish this, I have included the following code snippe ...

Unleashing the power of JavaScript: Sharing arrays and data structures effortlessly

Currently, I am utilizing HTML & JavaScript on the client side and NodeJs for the server side of my project. Incorporated in my form are multiple radio buttons. When the user clicks on the submit button, my intention is to post the results to the server. ...

Tips for activating a click event on a changing element within a Vue.js application

I am working on creating dynamically generated tabs with a specific range of time (from 8am to 9am). My goal is to automatically trigger a click event when the current time falls within this range. However, I am facing an issue where the ref is being ident ...

Employ the setInterval function to run a task every 15 minutes for a total of

I have a task that requires me to use setInterval function 5 times every 15 minutes, totaling one hour of work. Each value retrieved needs to be displayed in an HTML table. Below is the table: enter image description here For example, if it is 7:58 p.m. ...

Assign a class to the following element using an Angular 2 Directive

I have a dropdown menu and I want to incorporate an Angular2 directive to control the opening and closing of this dropdown. How can I apply the open class to the latest-notification div, knowing that my directive is applied to the button tag? Below is my ...

Modify the values of an object by utilizing the setter function

How can I utilize the setter method to update existing values of an object and perform mathematical operations? var obj = { set model(object) { //method's logic } }; obj = {x:10, y: 20, p: 15}; obj = { x:10, y: 20, p: 15 set mod ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...

Interacting with beans in JSF using JavaScript and AJAX techniques

In my user interface, I have a checkbox (CB) and two input fields (IT1, IT2) all connected to respective bean properties. My requirement is that when the CB is checked, I want IT1 and IT2 to be disabled and set to default values. However, when the CB is u ...

What causes the appearance of an HTTP header error and how can we identify the bug?

I tried to convert XML to JSON using two files which are included here. However, I keep encountering an error. Despite searching on SO for solutions, I haven't been able to find the answers. main.js /** SET ENGINE TO PUG */ app.set("views", ...

Creating the correct JSON structureHere is how you can format JSON

I have a snippet of javascript code that I'm utilizing with casperjs to iterate through links and retrieve data in json format. Below is the code snippet: casper.each(links, function (self, link) { this.thenOpen(link, function () { // obtain w ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

jquery for quick search

<form method="post" action="search.php"> Commence search: <input id="search" type="text" size="30" > <div id="search_results"></div> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code. ...

Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling. However, there is an issue that arises when the browser window is resized. The distance between the footer and ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...