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

After the ajax request is made in React JS, the column vanishes from the screen

Upon querying a node.js server's PostgreSQL database, I receive specific data that needs to be displayed in two separate tables. Each table consists of two columns. However, after the AJAX call, only the first column is being populated in the first ta ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

In Firefox, using the new Date function within a string does not function as expected

Why does the last log in the code snippet below not work in Firefox? (function() { String.prototype.toDate = function() { return new Date(this); }; console.log(Date.parse("2012-01-31")); console.log(new Date("2012-01-31")); c ...

Develop an interactive single-page scrolling system for seamless navigation between points

Creating a navigation that scrolls to the selected element when clicking on an <a> tag is my current project. I want it to animate smoothly during the transition. The navigation should go from: <a href="#Home">Home</a> To: <div id= ...

Using Jquery Datatables to populate with an asp.net webmethod through ajax calls

When it comes to using ajax with a webmethod to populate something or a table, I usually don't have any issues. However, I've been struggling to find a way to incorporate the jQuery datatables plug-in into my workflow. $.ajax({ type: "POST", ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

Increasing the selected date range by adding days manually in PHP - a comprehensive guide

Below is my jQuery AJAX request: I am attempting to send either the selected date or manually incremented days values to the controller. function myFunction(selected_first_date){ var get_my_value = $('#get_my_value').val(); $.ajax({ ...

Fetching data in a post request seems to be causing an issue with FormData image being

I've implemented a profile picture file upload system with the following HTML: <form enctype="multipart/form-data" id="imageUpload" > <img id="profileImage" src="./images/avatar.png& ...

Troubleshooting date range validation in jQuery

I am facing an issue in my code where I have a set of start and end date fields that need to be validated to ensure the start date comes before the end date. I am currently using the jQuery validation plugin for this purpose. For reference, here is the li ...

What are some effective ways to manage MySQL queries using asynchronous functions in JavaScript?

Can anyone assist me with my issue? I am new to JavaScript (Node.js) and attempting MySQL queries, but it seems like nothing is being output. I'm unsure how to address this. async function processArguments() { var result_customer = []; for(le ...

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

Periodically transmit information to a Google Script web application

I am currently working on a Google Script web app to automatically update data from a Google Sheet every 30 minutes. I initially attempted using the page refresh method, but encountered an issue where the web app would display a blank page upon refreshin ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

"Utilizing Dynamic Dropdown Options Pulled from Database and Automatically Refreshing List upon

I am facing a dilemma with displaying dropdown menus for Provinces and Cities, both of which have values coming from the database. While I can easily list the values for Provinces by querying all of them, my issue arises when it comes to displaying Cities. ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Unexpected error arises in Typescript despite code functioning properly

As part of a practice project where I'm focusing on using webpack, ES6, npm and Typescript implementation, I have successfully set up loaders for 'awesome-typescript-loader' and 'babel-loader', which are bundling the code properly. ...

Is it possible to make the v-toolbar-title fixed within a v-navigation-drawer using Vuetify?

Can the <v-toolbar-title> be fixed within a <v-navigation-drawer>? <v-card class="d-inline-block elevation-12"> <v-navigation-drawer hide-overlay permanent stateless height="440" value="true"> <v-toolbar color="whi ...