ASP.NET中的Ajax文件上传-处理程序看不到的文件

问题描述 投票:1回答:1

这是我第一次尝试通过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

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

Test.docx

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

javascript ajax vb.net ashx
1个回答
0
投票

尽管我的站点不是MVC,但是在查看该站点上的代码(https://www.yogihosting.com/jquery-file-upload/)并进行了视图更改之后,我能够使它正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.