ASP.NET is failing to receive Request.Files, returning null instead

I am attempting to upload an Excel file using XMLHttpRequest and FormData in ASP.NET, but I keep encountering the issue of Request.Files being null in ASP.NET. Below is the code I am using - can someone please assist me with this?

function BulkUploadUsers(e){
    var url = "/BC/Product/Modules/UserManagement/BulkUpload.aspx?action=import";
    var fd = new FormData();
    fd.append("ImportWorkOrderExcelFile", document.getElementById('ctl01_ImportFcpFile').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('X-CSRF-Token', document.getElementById("_RequestVerificationToken").value);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.send(fd);
}
    <div>
        <input type="file" id="ImportFcpFile" runat="server"  onchange="BulkUploadUsers(this)"/>       
    </div>

On the server side in the ASP.NET page:

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
                var aa = FindControl("ImportFcpFile");
                HttpPostedFile file = Request.Files["ImportUserExcelFile"];

        }
        catch (Exception ex)
        {
        }
    }

Answer №1

Here is my approach:

HttpFileCollection fileCollection = HttpContext.Current.Request.Files;
string savedfile = "";
            for (int i = 0; i < fileCollection.Count; i++)
            {
                try
                {
                    HttpPostedFile upload = fileCollection[i];
                    int f = fileCollection[i].ContentLength;
                    string filename = "/ProductImages/" + fileCollection[i].FileName;
                    upload.SaveAs(Server.MapPath(filename));
                    savedfile += fileCollection[i].FileName;
                }
                catch (Exception ex)
                {
                    List<string> ff = new List<string>();
                    ff.Add(ex.Message.ToString());
                    System.IO.File.WriteAllLines(Server.MapPath("/ProductImages/Error.txt"), ff);
                }

            }

This is the JavaScript code I implemented. Make sure not to overlook any details:

      function handleDnDFileSelect(event) {


           /* Read the list of all the selected files. */
          var files = event.dataTransfer.files;

           /* Consolidate the output element. */
           var form = document.getElementById('form1');

         var  fd= new FormData(form);

          for (i = 0; i < files.length; i++) {
               fd.append(files[i].name, files[i]);
           }
           var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
                 alert("Upload completed!");
             } else {
                 //alert("upload failed!");
             }
         };
         xhr.open('POST', "/BC/Product/Modules/UserManagement/BulkUpload.aspx");
        // xhr.setRequestHeader("Content-type", "multipart/form-data");
         xhr.send(fd);

        }

I simply loop through the files and save them with customized names as needed.

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

JavaScript call is not appearing during execution on asp.net

In the aspx page, there is an input element that looks like this: <input id="txtAllocAmt" type="text" class="txtAllocAmt" tabindex="2" size="10" name="Text1" runat="server" disabled="disabled" onfocus="javascript:SetOldAllocAmt(t ...

Rendering data in React using asynchronous JavaScript and XML (

I'm facing difficulties rendering my components with ajax data. I am unsure how to include a component inside my render method along with the ajax data. Below is my AccountPage.js code: import Close from '../../icons/Close' import Delete ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Tips for achieving a smooth scroll position maintenance

Currently, I have implemented the MaintainScrollPositionOnPostback feature in asp.net to maintain the position of the page after a postback. However, there is a noticeable jump when the page reloads - it initially loads at the top and then quickly jumps ...

Having trouble finding the correct route using an ajax request

Having trouble finding the correct route through an ajax call In my view, I have 2 HTML buttons that are generated using PHP <?php if ($comment_exist == null): ?> <p><input type ="button" id = "sb" value="I Comment"></p> &l ...

What is the best way to horizontally align my divs and ensure they stack properly using media queries?

My layout is not working as expected - I want these two elements to be side by side in the center before a media query, and then stack on top of each other when it hits. But for some reason, it's not behaving the way I intended. I've tried to ce ...

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

Switch up the image automatically after a short amount of time

Hello, I am a beginner in javascript and I have a question. Is it possible for javascript to automatically change an image after a few seconds? This is for my college project and it's quite messy. Below is the code snippet I am working with: <!DOC ...

Slider buttons are not appearing in Time Picker

I recently added a Time Picker to my project, but I'm experiencing an issue where the slider buttons for selecting time are not showing up. Could you please refer to this image: Checking the console, there don't seem to be any errors present. ...

Restricting the time frame in HTML 5

My form includes an input field with the type date <input type="date" id="datepick" name="mybirthday" placeholder="Birthdate(MM/DD/YYYY)" /> I am looking to restrict the date range that users can select. I specifically do not want users to be able ...

The PHP file is outputting the JavaScript code but it is not executing

My goal is to develop an Edit Modal. With the necessary html code in place, I proceeded to write the following javascript/jquery script: <script type='text/javascript'> $(function() { <?php $q = $db->query("select * f ...

Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if an ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Storing JSON data in a MongoDb database using the Sails.js framework

I'm looking to build my database using an external API. To begin, I've created a function called loadData(req, res){} in my DBController that retrieves data from the API in JSON format. Now, I want to save this imported JSON data into my mongoDB ...

What causes the axios Library to fail in initiating a request if the API call does not begin with "https://"?

This issue has been resolved, but I still want to ask it in order to gain a better understanding of the underlying processes. So, I am using an API to retrieve data on the current weather in a specific city. The API call (as per the provider's documen ...

Trouble with useEffect not triggering in NextJS 13.4 (app router) application

When trying to fetch data from the next API route, I encountered an issue where the useEffect method did not trigger on page reload. Additionally, I was unable to make this component async as Next.js does not allow async functions in client components. pa ...

Launching a Popup in ASP.NET followed by a Redirect

I have a unique custom CSS/HTML popup lightbox along with a form that contains a button. My objective is, upon clicking the button: to open the popup followed by using Thread.Sleep and finally carry out a Response.Redirect to a different page. Do you th ...

Excessive data flooding the console through Socket.io until the Payload reaches an unsustainable size

This snippet of code forms part of a chat application developed using React Native, functioning through a socket.io server. const Message = ({text, isSent}) => { return ( <View style={[styles.messageContainer, isSent ? styles.sentMessage : styl ...

What is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

Ways to alter an array of objects without using a loop

The following code is functioning properly: for(let i=0;i< this.Array.length ; i++){ if(this.Array[i].propertyObject.hasOwnProperty('header')) this.Array[i].ColumnName = this.Array[i].propertyObject.header; } I am int ...