简体   繁体   中英

Ajax file upload in ASP.NET - files not seen by handler

This is the first time I've attempted to upload files via Ajax and.ashx. I'm using FireFox 75.0 and when I look at my web console, I added a Breakpoint on frm.append(files[i], files[i].name); and I see the file and/or files (file input has "multiple" attribute) that are appended to the FormData() object in my script. The file input control (HTML5) has an "onchange" event which fires the javascript. The JavaScript seems to be working correctly. My handler file, however, does not see the HttpFileCollection. I can't figure out why this is not working so I'm looking for some help.

Here is the ASPX page code:

<!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>

Here is my handler code:

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

In the Try Catch block of my handler, where it checks for the file count, it doesn't see the files. It always returns "No files found," When I click on the network tab in my web console: I see the file objects - Content-Disposition; form-data; name="[object File]"

Test.docx

I would greatly appreciate if someone could tell me what I'm missing and how to fix it. Thanks!

Although my site is not MVC, after viewing the code on this site ( https://www.yogihosting.com/jquery-file-upload/ ), and making a view alterations, I was able to get this working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM