ASP.NET file uploads using Ajax - handler unable to detect uploaded files

I am embarking on my first attempt at uploading files through Ajax and .ashx. My browser of choice is FireFox 75.0. Upon inspecting the web console, I set a Breakpoint on

frm.append(files[i], files[i].name);
. I can see the files being appended to the FormData() object in my script. The file input control (HTML5) triggers a JavaScript event with an "onchange" attribute. The JavaScript functionality appears to be working as expected. However, my handler file is not able to detect the HttpFileCollection. I am puzzled by this issue and seeking assistance to resolve it.

Below is the code snippet from the ASPX page:

<!DOCTYPE html>

<html>
<head runat="server">
    <title></title>
    <link href="../../assets/css/bootstrap.css" rel="stylesheet" />
    <link href="../../assets/css/OLF_style.css" rel="stylesheet" />
    <script type="text/javascript" src="../../scripts/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="../../scripts/bootstrap.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div class="row" id="rw_5887" style="border-bottom: 1px inset #e0e0e0;">
    <div class="col-sm-3 txtmd txright" style="padding: 4px 10px 4px 4px;color:#333333"><label for="DocUpload">Upload File</label></div>
    <div class="col-sm-9 txtmd" style="padding: 4px 4px 4px 4px;;color:#999999"><img id="upload_files" src="../../assets/img/btn_upload01.png" alt="Upload File" style="margin: 7px 10px 0px 10px" /><input id='fupDocUpload' type='file' accept=".docx;.doc" multiple='multiple' class='form-control' style='display:none;height:0px;width:0px' onchange="doFileSelect();" /><div id="uploadstatus" style="display: inline"></div>
<br /><progress id="fileProgress" style="display: none"></progress>
        <br /><div id="dvFileUploads" class="gradlt txtreg rnd" style="height: 60px;width:90%;"></div><input type="hidden" id="hfFilesUploaded" />
    </div>
</div>
    </form>
    <script type="text/javascript">
            var fileupload = $("#fupDocUpload");
            var imgbtn = $("#upload_files");
            imgbtn.click(function () {
                $(fileupload).click();
            });
        function doFileSelect() {
            $("#uploadstatus").html('Upload in progress...');
            var fileInput = $('#fupDocUpload').get(0);
            var frm = new FormData();
            var files = [];
            files = fileInput.files;
            var ufiles = $("#hfFilesUploaded").val();
            for (var i = 0; i < files.length; i++) {
                    frm.append(files[i], files[i].name);
                    if ($("#hfFilesUploaded").val() == '') {
                        $("#dvFileUploads").append(files[i].name);
                        $("#hfFilesUploaded").val(files[i].name);
                    } else {
                        $("#dvFileUploads").append(', ' + files[i].name);
                        $("#hfFilesUploaded").val(ufiles + ',' + files[i].name);
                    }
            }
               $.ajax({
                   url: 'handler/UploadHandler.ashx',
                   type: 'POST',
                   data: frm,
                   cache: false,
                   contentType: false,
                   processData: false,
                   success: function (result) {
                       $("#fileProgress").hide();
                       $("#uploadstatus").html(result);
                       window.setTimeout(clrStatus, 2000);
                   },
                   xhr: function () {
                       var fileXhr = $.ajaxSettings.xhr();
                       if (fileXhr.upload) {
                           $("progress").show();
                           fileXhr.upload.addEventListener("progress", function (e) {
                               if (e.lengthComputable) {
                                   $("#fileProgress").attr({
                                       value: e.loaded,
                                       max: e.total
                                   });
                               }
                           }, false);
                       }
                       return fileXhr;
                   }
               });
        }
        function clrStatus() {
            var status = $('#uploadstatus').html('');
        }
    </script>
</body>
</html>

And here is the code snippet from my handler:

Imports System
Imports System.Web
Imports System.IO

Public Class UploadHandler : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Response.ContentType = "text/html"
        Dim files As HttpFileCollection = context.Request.Files()
        Dim UploadPath As String = ConfigurationManager.AppSettings("FormFileUpload")
        'Dim strFiles As String = String.Empty
        Try
            If context.Request.Files.Count = 0 Then
                context.Response.Write("<img src=""../../assets/img/NotAllowed.png"" alt="""" style=""margin-left: 5px; margin-right: 5px"" /> No Files Found!")
            Else
                For i As Integer = 0 To files.Count - 1
                    Dim file As HttpPostedFile = files(i)
                    Dim fname As String = String.Empty
                    fname = file.FileName
                    fname = Replace(fname, " ", "_") 'Replace spaces in file name
                    fname = Path.Combine(context.Server.MapPath(UploadPath), fname)
                    file.SaveAs(fname)
                Next
                context.Response.Write("<img src=""../../assets/img/CkMark.png"" alt="""" style=""margin-left: 5px"" />")
            End If
        Catch ex As Exception
            context.Response.Write("<img src=""../../assets/img/NotAllowed.png"" alt="""" style=""margin-left: 5px; margin-right: 5px"" /> Error!" & ex.ToString())
        End Try
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Despite my efforts, the Try Catch block in my handler is unable to detect any files, always displaying "No files found!" message. When checking the network tab in the web console, I can see the file objects present - Content-Disposition: form-data; name="[object File]"

The file "Test.docx" is attempted to be uploaded.

I am seeking guidance on resolving this issue. Any help would be greatly appreciated. Thank you!

Answer №1

Even though my site doesn't follow the MVC pattern, I found inspiration from the code provided on the following site () and with a few adjustments, I successfully implemented the functionality.

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

What are the best practices for creating documentation in ReactJS?

I need to generate documentation in a .doc file format for each component defined in our ReactJS application. I am seeking an npm package that can assist with this process by extracting code and comments from my components and converting them into docume ...

Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value en ...

Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below: <td onclick="openFile('<?php echo htmlentities ($row['name'])?>',' <?php echo htmlentities ($row['content'])?>')"> <a href="#nf" dat ...

JSplumb - retrieve a connection targeting a particular endpoint

There are multiple endpoints on my elements. By using the following code snippet, I am able to retrieve all the connections linked to a specific element: // My JSPlumb instance object is named plumber connSet = plumber.getConnections({target:eltID}); Th ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

Create a file by generating JSON data in an ASP.NET MVC post controller and then return the file

I am currently working on an ajax post request: function downloadElevationMap() { var jsonData = ko.toJSON(mod.SelectedItem); $.ajax({ url: '/Home/GetData/', type: 'POST', contentType: "application/jso ...

Error: Jsonp callback not functioning properly on Internet Explorer

I have been using JSONP to retrieve data from an API through AJAX. After testing my code on Firefox and Chrome, it has worked flawlessly in these browsers. The link I am utilizing follows this format: www.placeholder.com/foo/?jsonp=dataCallback Yet, ...

How can I dynamically update a React/Next.js page as the server completes different stages of a complex action?

Currently, my aim is to develop a single-page application that relies on one major back-end process. This procedure is initiated by a singular string input. The various stages involved and the outcomes are as follows: It takes about 20ms to display/render ...

What is the best approach to updating a single item within a list using React Context?

React context is great, but I feel like there's something missing in my understanding of it. Let's say I have a list of todos and its corresponding provider set up like this: const Home = () => ( <div className="container"> <T ...

Console shows successful jQuery ajax request, but the callback function is not being executed

I've been working on a jQuery POST request that's been giving me some trouble. Here is a snippet of the code I'm using: $.ajax("/myurl",{ data:{ ... }, mimeType:"application/json", dataType:"application/json", me ...

Display information in the DIV element after using the .focus() method in JQuery

Imagine I have a form structured like this: <select id="model"/> <input type="text" id="serial"/> <label>Packing <div id="packing" name="packing"></div></label> <br/> <input id="pack1" type="radio" class="pack" ...

JQuery submit event not triggering object setting

I'm looking to gather input values from a form and store them in an object for an offer. After trying the following code on submit: $(document).ready(function(){ $('#formOffre').on('submit', function(e) { e.preventDefault ...

Is there a way to adjust the dimensions of Google charts within a Bootstrap tab for a more customized appearance?

I've been working on a page that features tab navigation using Twitter Bootstrap and I want to include Google charts within each tab's content. However, I've encountered an issue where the charts are appearing in different sizes despite spec ...

"Utilizing AngularJS to asynchronously send an HTTP POST request and dynamically update

I've been working on an angularjs chat module and have come across a challenge. I developed an algorithm that handles creating new chats, with the following steps: Click on the 'New Chat' button A list of available people to chat with wil ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Error: The reference to WEBGL has not been properly defined

Within my HTML, the code snippet below is causing an issue: if (WEBGL.isWebGLAvailable()==false) { document.body.appendChild(WEBGL.getWebGLErrorMessage()); } Upon running this code, the following error appears in the console: Uncaught ReferenceErr ...

What is the best way to upgrade to a specific version of a child dependency within a module?

npm version: 7.24.2 Looking for assistance on updating a child dependency. The dependency in question is: vue-tel-input This dependency relies on libphonenumber-js with version ^1.9.6 I am aiming to update libphonenumber-js to version ^1.10.12. I have ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...

My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js. After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project. However, I encountered some interesting error ...