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

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

ASPX

  

处理器

 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "multipart/form-data"; context.Response.Expires = -1; try { HttpPostedFile postedFile = context.Request.Files["file"]; string savepath = HttpContext.Current.Server.MapPath("~/assets/common/CompetitionEntryImages/"); var extension = Path.GetExtension(postedFile.FileName); if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath); var id = Guid.NewGuid() + extension; if (extension != null) { var fileLocation = string.Format("{0}/{1}", savepath, id); postedFile.SaveAs(fileLocation); context.Response.Write(fileLocation); context.Response.StatusCode = 200; } } catch (Exception ex) { context.Response.Write("Error: " + ex.Message); } } 

jQuery的

 $(document).ready(function () { email = $("input[id$='emailHV']").val(); alert(email); $('#aspnetForm').attr("enctype", "multipart/form-data"); }); $('#').on('click', function (e) { e.preventDefault(); var fileInput = $('#ctl00_PageContent_Signup_ctl06_MWFileUpload_FileUpload1'); var fd = new window.FormData(); fd.append('file', fileInput.files[0]); $.ajax({ url: '/charity-challenge/MWFileUploadHandler.ashx', data: fd, processData: false, contentType: false, type: 'POST', success: function (data) { alert(data); } }); }); 

错误

在此处输入图像描述

HTML

   

EDITS

最后,我通过做这些事来形成数据

 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); 

完整的工作代码

 $('#').on('click', function (e) { e.preventDefault(); var fileInput = $('#'); 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") { $('#').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(); } }); }); 

经过整整一个下午的敲打,当我意识到你指定了“处理程序”而不是“服务”的巨大差异时,我回到了这个问题/解决方案。 :)另外对于一个可以在后面运行这个jquery的工作的hander我去了https://github.com/superquinho/jQuery-File-Upload-ASPnet并修剪了我不需要的东西。 这是我正在使用的处理程序代码(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 
 $("#file-upload") 

应该

 $("#ctl00_PageContent_Signup_ctl06_MWFileUpload_file-Upload") 

通过使用ClientIdMode属性,将服务器代码上的文件上载控件更改为具有静态服务器端ID。 像这样:

  

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

在您的Web配置文件中使用它

      

你可以用这个:

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