Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the beforerequest function, but still had no luck.

Below is the code snippet:

Ext.Ajax.request({
            url: 'url',
            method: 'Post',
            headers : {'Authorization':'Bearer '+access_token},
            form: form,
            isUpload: true,
            params: {id: id},

After some research, I found out that sending a header in form submit might not be possible. Are there any alternative methods I can explore to achieve my goal?

Answer №1

Here's a way to upload files using the FormData object and XMLHttpRequest:

 var xhr = new XMLHttpRequest();

 xhr.open('POST', url, true);

 var formData = new FormData();

 for (var i= 0; i< files.length; i++) {
      var file = files[i];
      formData.append(file.name, file);
 }

 xhr.onreadystatechange = function(eOpts) {
      if (xhr.readyState !== 4 || me.isDestroyed) {
            return;
      }
      ......
 };

 xhr.send(formData);

Learn more about FormData

Answer №2

It's fascinating, however, I was unable to locate a solution using ExtJS.

Check out this example demonstrating how you can include headers in a POST request with a file shared by Gabriele Romanato:

// Locate the input file within the HTML document
const fileInput = document.getElementById("file-input");

// Create an instance of XMLHttpRequest
const xhr = new XMLHttpRequest();

// Set up the callback function to handle the server response
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // The file has been successfully uploaded
    console.log("File successfully uploaded!");
  }
};

// Open a connection to the server
xhr.open("POST", "/upload-file", true);

// Set the "Content-Type" header to "multipart/form-data"
xhr.setRequestHeader("Content-Type", "multipart/form-data");

// Create a FormData object and add the selected file
const formData = new FormData();
formData.append("file", fileInput.files[0]);

// Send the request to the server using the send() method
xhr.send(formData);

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

Using setTimeout in Node.js

I've been struggling to find a solution for slowing down the timeout in my code. The issue is that it runs too quickly, and I can't seem to figure out how to adjust it using Request. Everything else in the code works perfectly. var Scraper = fun ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Transforming form inputs into JSON structure

<form name = 'test' > <input type='text' name = 'login'> <input type='email' name = 'email'> </form> When I try to convert the form data using JSON.serialize($(form)).serial ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

React.js: Why does the array index change after dropping an element?

When I create a table with items in a checkbox list, the issue arises; after selecting and submitting some items, the index of the remaining items changes. Consequently, re-submitting the remaining items becomes impossible. Below is my code snippet: expo ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Retrieve the value of a property in a JavaScript object by specifying a dynamic key for the property

As I work on my current project, I find myself immersed in a world of SVG animations. The challenge lies in triggering these animations as the user scrolls down to view the SVGs. To address this, I took the approach of creating functions for each Snap.SVG ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Issue with Ajax Form Handling

I am struggling to get my ajax form post working correctly. It seems like there might be an issue with the $.ajax lines in my code. When the code reaches the $.ajax portion, the console.log() function stops working and the form redirects normally to the aj ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

jQuery Ajax form submission encountering issues

I created a form dynamically with the help of jQuery. Here is the code: <form id="editorform" accept-charset="utf-8" method="post" name="editorform" action="menuupdate"> <div> <input id="updateItem" type="submit" value="Update"& ...

Encountering a 304 status error in the HTTP GET response after deploying a React app on Netlify

After deploying my react application on Netlify, I used the npm run build command to create the local scripts and manually deployed them in production mode on Netlify. The build scripts were generated on my local machine and then uploaded to the Net ...

What Causes My Issue with $(document).ready()?

Currently delving into the world of jQuery, but I've hit a roadblock. Below is the snippet in question: var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.4.1.min.js'; script.type = " ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...