首页 > 解决方案 > ASP.NET 中的 Ajax 文件上传 - 处理程序看不到的文件

问题描述

这是我第一次尝试通过 Ajax 和 .ashx 上传文件。我正在使用 FireFox 75.0,当我查看我的 Web 控制台时,我添加了一个断点frm.append(files[i], files[i].name);,我看到了附加到我脚本中 FormData() 对象的文件和/或文件(文件输入具有“多个”属性) . 文件输入控件 (HTML5) 有一个触发 javascript 的“onchange”事件。JavaScript 似乎工作正常。但是,我的处理程序文件看不到 HttpFileCollection。我无法弄清楚为什么这不起作用,所以我正在寻求帮助。

这是 ASPX 页面代码:

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

这是我的处理程序代码:

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

在我的处理程序的 Try Catch 块中,它检查文件计数,它看不到文件。它总是返回“未找到文件!” 当我单击 Web 控制台中的网络选项卡时,我会看到文件对象 - Content-Disposition: form-data; 名称="[目标文件]"

测试.docx

如果有人能告诉我我缺少什么以及如何解决它,我将不胜感激。谢谢!

标签: javascriptajaxvb.netashx

解决方案


虽然我的网站不是 MVC,但在查看了本网站 ( https://www.yogihosting.com/jquery-file-upload/ ) 上的代码并进行了视图更改后,我能够让它工作。


推荐阅读