"Enhancing User Experience with Ajax Uploads in ASP.NET

I am attempting to upload text content using ajax for later parsing. Here is my JavaScript code:

 $("#fuFile").change(function () {
            var fileInput = document.getElementById("fuFile");
            var file = fileInput.files[0];
            var formdata = new FormData();
            formdata.append('file', file);

            var xhr = new XMLHttpRequest();
            xhr.open("POST", 'testhandler.ashx', true);
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.setRequestHeader("X-File-Name", file.name);
            xhr.setRequestHeader("Content-Type", "application/octet-stream");
            xhr.send(formdata);              

 });

Where fuFile represents the file input, and testhandler.ashx is the server handler responsible for receiving the uploaded file. (I actually utilize another handler to parse the file content.)

However, when I attempt this:

HttpFileCollection fc = context.Request.Files;

No files are returned. It does work in IE for some reason.

Yet, if I try to access the input stream:

StreamReader stream = new StreamReader(context.Request.InputStream);
    string text = stream.ReadToEnd();

The text variable ends up containing both the HTTP headers and the File Content.

------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..)

Although this is acceptable, I have previously utilized a plugin:

This plugin only provided me with the file content, from which I could retrieve data via InputStream without any HTTP header received.

This solution was ideal, but I aim to create an upload script that doesn't rely on plugins. Simply upload, parse, and return results. Efficient and straightforward.

Hence, my query is: How can I extract the file content exclusively from an Ajax XHR upload, across all browsers?

Answer №1

This solution has been effective for me and I believe it could be helpful for you too

Here is my JavaScript function :

$("#fuFile").click(function () {
    var fileInput = document.getElementById("fuFile");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();

    xhr.open("POST", 'http://localhost:63186/UploadFile.ashx');

    xhr.send(fd);

});

And here is my handler implementation :

string filePath = "~/Files/";

        //write your handler implementation here.
        if (context.Request.Files.Count <= 0)
        {
            context.Response.Write("No file uploaded");
        }
        else
        {
            for (int i = 0; i < context.Request.Files.Count; ++i)
            {
                HttpPostedFile file = context.Request.Files[i];
                 var fileInfo = new FileInfo(file.FileName);
                file.SaveAs(context.Server.MapPath(filePath + fileInfo.Name));
                context.Response.Write("File uploaded");
            }
        }

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

Ways to mandate adjusting an option in <select> tag

Using the code $('select').change(function(){alert('changed');});, I am able to trigger an alert every time the option is changed. However, I also need to trigger the alert when the default option, which is the first one in the list, is ...

Learn how to implement a conditional class binding in Vue 3, and discover how to apply additional classes when a specific condition is met

As a newcomer to Vue.js 3, I am wondering how to implement a conditional class binding in Vue 3. Specifically, I would like to achieve the following logic: if router.path != '/', then add the class 'nav-bar-two'; otherwise, do not apply ...

Animate in Css3 before the object enters the user's view

Currently, I am utilizing CSS3 animate it from Despite following their instructions, the children within the animation activate prior to entering the viewport. Is this a common issue or is there a specific meta tag required? Your assistance is greatly ap ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...

Preventing window resize from affecting print screen content in Angular 8

I'm struggling with a print button feature in my Angular 8 project. When the window is resized, the content within the print window also resizes, which is not the behavior I want. I've tried a couple of solutions, but nothing has worked so far: 1 ...

How to exchange variables and trigger events between jQuery and C# using AJAX

Hey there! So I've got this jQuery snippet that's using jqvmaps to display a world map and interact with it: <script type="text/javascript" lang="js> $(document).ready(function(){ jQuery('#vmap').vectorMap( ...

Struggling to showcase API data on React interface

I am working on fetching data from a private API and displaying it on a web page. My frontend is built using React JS, while my backend uses Node with Express and Axios. Everything seems to be working fine until the point where I need to display the fetche ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Include a variable in an array object?

Yesterday I had some assistance with looping through my var arr to search the system for .png files. The code snippet used was: const fs = require('fs'); const path = require('path'); const imageDir = '/var/scraper/public/image ...

Implementing MySQL in JavaScript code leads to various possibilities

I am working on a web application that requires retrieving values from a MySQL database. The process involves: PHP code generates an HTML page successfully. Clicking a button updates a cookie, which also works. Using the cookie in a MySQL query, which is ...

Ways to obtain the text content of the chosen item in a dropdown menu

I am facing an issue where I am unable to retrieve the selected value from a dropdown list; instead, it always displays '-Select-' Snippet of Code: if (Convert.ToBoolean(ViewState["Response"])) { String InvoiceNo= Convert.ToS ...

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

Error retrieving Facebook access token using Node.js https.get()

I've been working on setting up a Facebook login flow in my node.js app, but I'm facing an issue where the access token isn't returning from the Facebook API when using node's https.get() method. Interestingly, I am able to retrieve the ...

"Enhance your data management with a dynamic React JS table

While attempting to modify the table from the react js docs linked here, I encountered some unexpected issues as shown in the screenshots below. https://i.sstatic.net/u2ck6.png We are trying to filter based on "lBird" https://i.sstatic.net/vCta4.png Th ...

Is it more efficient to perform data sorting on the client side or the server side?

My current task involves fetching data from a server and showcasing it through GWT on the client side. The use of GWT is flexible - it can be swapped out for Ajax calls or transformed into a standalone application rather than just a web app. One dilemma ...

Accessing Firebug in Selenium webdriver is a straightforward process that involves downloading and

Seeking guidance on how to approach a requirement using Selenium webdriver as I am new to it. The requirement entails: Select the note icon to open a 'note' pop up. Then, open Firebug within the pop-up. Access the script option in Firebug, se ...

The Textarea's style is automatically overridden by the element's style attribute

On my aspx page, there is a textarea element: <div style=" position: absolute; top: 45px; bottom: 5px; left: 5px; right: 5px"> <textarea id="code" name="code" runat="server" wrap="off" style="clear ...

Having trouble retrieving the complete count of elements within Playwright

For my automation suite, I decided to incorporate a Page Object Design pattern. In one of the test cases involving a simple table on the website, I encountered an issue while trying to obtain the total number of elements. Error: locator.waitFor: Target c ...

Does a legitimate array monad transformer exist?

I have successfully implemented the single linked list monad transformer, however, I am struggling to get its array counterpart functioning properly. The issue stems from a grouping effect that restricts the transformer's validity to commutative base ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...