Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery ajax和asp.net处理程序上载文件_Asp.net_Jquery_File Upload_Ashx - Fatal编程技术网

使用jquery ajax和asp.net处理程序上载文件

使用jquery ajax和asp.net处理程序上载文件,asp.net,jquery,file-upload,ashx,Asp.net,Jquery,File Upload,Ashx,我正在努力让这个工作,但我在上传文件时遇到了错误 ASPX 滑动分页 完整工作代码 $('#')。在('click',函数(e){ e、 预防默认值(); var fileInput=$(“#”); var fileData=fileInput.prop(“files”)[0];//从文件字段获取文件的属性 var formData=new window.formData();//正在创建formData类的对象 append(“file”,fileData);//将名为file的参数与file

我正在努力让这个工作,但我在上传文件时遇到了错误

ASPX 滑动分页 完整工作代码
$('#')。在('click',函数(e){
e、 预防默认值();
var fileInput=$(“#”);
var fileData=fileInput.prop(“files”)[0];//从文件字段获取文件的属性
var formData=new window.formData();//正在创建formData类的对象
append(“file”,fileData);//将名为file的参数与file_字段的属性一起追加到form_数据中
formData.append(“用户\电子邮件”,电子邮件);
$.ajax({
url:“/charity challenge/MWFileUploadHandler.ashx”,
数据:formData,
processData:false,
contentType:false,
键入:“POST”,
成功:功能(数据){
var obj=$.parseJSON(数据);
如果(对象状态代码==“正常”){
$('#').val(obj.ImageUploadPath);
$('.result message').html(obj.message.show();
}否则如果(obj.StatusCode==“错误”){
$('.result message').html(obj.message.show();
}
},
错误:函数(errorData){
$('.result message').html(“上载文件时出现问题。”).show();
}
});
});
应该是

$("#ctl00_PageContent_Signup_ctl06_MWFileUpload_file-Upload")
查看如何使用
ClientIdMode
属性将服务器代码上的文件上载控件更改为具有静态服务器端id。像这样:

<asp:FileUpload ID="FileUpload1" runat="server" CssClass="file-upload-dialog" ClientIdMode="Static" />


然后,您可以确定客户端代码中控件的ID将是
FileUpload1

经过一个下午的讨论,当我意识到您指定的是“处理程序”而不是“服务”时,我又回到了这个问题/解决方案(大的区别:)同样对于一个可以在后面运行jquery的工作人员,我去了那里,删掉了我不需要的东西。下面是我正在使用的处理程序代码(VS2012)。正如你所看到的,我现在只在csv上传时使用它

Imports System
Imports System.Web
Imports System.Data

Public Class FileUpload : Implements IHttpHandler, IReadOnlySessionState
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Try
            Select Case context.Request.HttpMethod
                Case "POST"
                    Uploadfile(context)
                    Return

            Case Else
                context.Response.ClearHeaders()
                context.Response.StatusCode = 405
                Return
        End Select

    Catch ex As Exception
        Throw
    End Try

End Sub

Private Sub Uploadfile(ByVal context As HttpContext)

    Dim i As Integer
    Dim files As String()
    Dim savedFileName As String = String.Empty
    Dim js As New Script.Serialization.JavaScriptSerializer

    Try

        If context.Request.Files.Count >= 1 Then

            Dim maximumFileSize As Integer = ConfigurationManager.AppSettings("UploadFilesMaximumFileSize")

            context.Response.ContentType = "text/plain"
            For i = 0 To context.Request.Files.Count - 1
                Dim hpf As HttpPostedFile
                Dim FileName As String
                hpf = context.Request.Files.Item(i)

                If HttpContext.Current.Request.Browser.Browser.ToUpper = "IE" Then
                    files = hpf.FileName.Split(CChar("\\"))
                    FileName = files(files.Length - 1)
                Else
                    FileName = hpf.FileName
                End If


                If hpf.ContentLength >= 0 And (hpf.ContentLength <= maximumFileSize * 1000 Or maximumFileSize = 0) Then
                    Dim d As Date = Now
                    savedFileName = HttpRuntime.AppDomainAppPath & "CSVLoad\" + d.Year.ToString + d.DayOfYear.ToString + d.Hour.ToString + d.Minute.ToString + d.Second.ToString + d.Millisecond.ToString + ".csv"

                    hpf.SaveAs(savedFileName)

                Else

                End If
            Next

        End If

    Catch ex As Exception
        Throw
    End Try

End Sub

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

End Class
导入系统
导入系统.Web
导入系统数据
公共类FileUpload:实现IHttpHandler、IReadOnlySessionState
Public Sub-ProcessRequest(ByVal上下文作为HttpContext)实现IHttpHandler.ProcessRequest
尝试
选择Case context.Request.HttpMethod
案件“员额”
上载文件(上下文)
返回
其他情况
context.Response.ClearHeaders()
context.Response.StatusCode=405
返回
结束选择
特例
扔
结束尝试
端接头
私有子上载文件(ByVal上下文作为HttpContext)
作为整数的Dim i
将文件设置为字符串()
Dim savedFileName As String=String.Empty
Dim js作为新的Script.Serialization.JavaScriptSerializer
尝试
如果context.Request.Files.Count>=1,则
Dim maximumFileSize As Integer=ConfigurationManager.AppSettings(“UploadFilesMaximumFileSize”)
context.Response.ContentType=“text/plain”
对于i=0到context.Request.Files.Count-1
将hpf设置为HttpPostedFile
将文件名设置为字符串
hpf=context.Request.Files.Item(i)
如果HttpContext.Current.Request.Browser.Browser.ToUpper=“IE”,则
files=hpf.FileName.Split(CChar(“\\”)
FileName=文件(files.Length-1)
其他的
FileName=hpf.FileName
如果结束

如果hpf.ContentLength>=0且(hpf.ContentLength),请在web配置文件中使用此选项

<system.webServer>
 <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <add name="AjaxFileUploadHandler" verb="*" 
      path="AjaxFileUploadHandler.axd"
      type="AjaxControlToolkit.AjaxFileUploadHandler, 
      AjaxControlToolkit"/>
</handlers>

您可以使用以下功能:

$("#<% = FileUpload1.clientID %>")
$(“#”)

您可以发布由
生成的HTML吗?另外,在控制台选项卡中,您可以键入
var fileInput=$(“#文件上载”)
并检查它的值请参见我的编辑…控制台中显示未定义..我不知道为什么!您正在查找id为
的元素文件上载
。生成的html中没有具有此id的元素。请尝试DaveHogan tip。尝试解决方案但没有成功…仍然使用html b中生成的id尝试相同的错误y在jquery中处理..仍然没有运气..相同的错误好的技巧是使用ClientIDMode是静态的,这样可以确保元素客户端ID匹配。(与button控件相同)。是的,这是真的,但我不能这样做,因为这可能会导致其他问题。但我在jquery中放置相同的id,那么为什么会出现错误?确保id绝对匹配,并在浏览器的监视/控制台窗口中确认
var fileInput
的结果。如果id存在,则不会得到“未定义”。se请编辑我的内容…我通过将文件数据附加到表单对象来实现它
$('#<%= btnUpload.ClientID %>').on('click', function (e) {
            e.preventDefault();
            var fileInput = $('#<%= FileUpload1.ClientID %>');
            var fileData = fileInput.prop("files")[0];   // Getting the properties of file from file field
            var formData = new window.FormData();                  // Creating object of FormData class
            formData.append("file", fileData); // Appending parameter named file with properties of file_field to form_data
            formData.append("user_email", email);
            $.ajax({
                  url: '/charity-challenge/MWFileUploadHandler.ashx',
                  data: formData,
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function (data) {
                        var obj = $.parseJSON(data);
                        if (obj.StatusCode == "OK") {
                              $('#<%= imagePath.ClientID %>').val(obj.ImageUploadPath);
                              $('.result-message').html(obj.Message).show();
                        } else if (obj.StatusCode == "ERROR") {
                              $('.result-message').html(obj.Message).show();
                        }
                  },
                  error: function (errorData) {
                        $('.result-message').html("there was a problem uploading the file.").show();
                  }
            });
      });
$("#file-upload") 
$("#ctl00_PageContent_Signup_ctl06_MWFileUpload_file-Upload")
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="file-upload-dialog" ClientIdMode="Static" />
Imports System
Imports System.Web
Imports System.Data

Public Class FileUpload : Implements IHttpHandler, IReadOnlySessionState
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Try
            Select Case context.Request.HttpMethod
                Case "POST"
                    Uploadfile(context)
                    Return

            Case Else
                context.Response.ClearHeaders()
                context.Response.StatusCode = 405
                Return
        End Select

    Catch ex As Exception
        Throw
    End Try

End Sub

Private Sub Uploadfile(ByVal context As HttpContext)

    Dim i As Integer
    Dim files As String()
    Dim savedFileName As String = String.Empty
    Dim js As New Script.Serialization.JavaScriptSerializer

    Try

        If context.Request.Files.Count >= 1 Then

            Dim maximumFileSize As Integer = ConfigurationManager.AppSettings("UploadFilesMaximumFileSize")

            context.Response.ContentType = "text/plain"
            For i = 0 To context.Request.Files.Count - 1
                Dim hpf As HttpPostedFile
                Dim FileName As String
                hpf = context.Request.Files.Item(i)

                If HttpContext.Current.Request.Browser.Browser.ToUpper = "IE" Then
                    files = hpf.FileName.Split(CChar("\\"))
                    FileName = files(files.Length - 1)
                Else
                    FileName = hpf.FileName
                End If


                If hpf.ContentLength >= 0 And (hpf.ContentLength <= maximumFileSize * 1000 Or maximumFileSize = 0) Then
                    Dim d As Date = Now
                    savedFileName = HttpRuntime.AppDomainAppPath & "CSVLoad\" + d.Year.ToString + d.DayOfYear.ToString + d.Hour.ToString + d.Minute.ToString + d.Second.ToString + d.Millisecond.ToString + ".csv"

                    hpf.SaveAs(savedFileName)

                Else

                End If
            Next

        End If

    Catch ex As Exception
        Throw
    End Try

End Sub

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

End Class
<system.webServer>
 <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <add name="AjaxFileUploadHandler" verb="*" 
      path="AjaxFileUploadHandler.axd"
      type="AjaxControlToolkit.AjaxFileUploadHandler, 
      AjaxControlToolkit"/>
</handlers>
$("#<% = FileUpload1.clientID %>")