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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17109357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:27:29  来源:igfitidea点击:

file upload using jquery ajax and asp.net handler

asp.netjqueryfile-uploadashx

提问by patel.milanb

I am trying hard to get this working but i ma getting error while uploading file.

我正在努力使其正常工作,但在上传文件时出现错误。

ASPX

ASPX

<asp:FileUpload ID="FileUpload1" runat="server" CssClass="file-upload-dialog" />
<asp:Button runat="server" ID="btnUpload" CssClass="btn upload" Text="Upload" />

Handler

处理程序

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



$('#<%= btnUpload.ClientID %>').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);
                  }
            });
      });

Error

错误

enter image description here

在此处输入图片说明

HTML

HTML

<input type="file" name="ctl00$PageContent$Signup$ctl06$MWFileUpload$FileUpload1" id="ctl00_PageContent_Signup_ctl06_MWFileUpload_FileUpload1" class="file-upload-dialog">

 <input type="submit" name="ctl00$PageContent$Signup$ctl06$MWFileUpload$btnUpload" 
value="Upload" onclick="javascript:WebForm_DoPostBackWithOptions(new 
WebForm_PostBackOptions(&quot;ctl00$PageContent$Signup$ctl06$MWFileUpload$btnUpload&quot;, 
&quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" 
id="ctl00_PageContent_Signup_ctl06_MWFileUpload_btnUpload" class="button">

EDITS

编辑

Finally, i got it working by doing these things to form data

最后,我通过做这些事情来形成数据来让它工作

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

FULL WORKING CODE

完整的工作代码

$('#<%= 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();
                  }
            });
      });

回答by HelloW

After a whole afternoon of banging, I came back to this question/solution when I realized that you had specified "handler" rather than "service" big difference. :) Also for a working hander that can run this jquery in the back I went to https://github.com/superquinho/jQuery-File-Upload-ASPnetand trimmed out what I didn't need. Here is the handler code that I am using (VS2012). As you can see I only use it right now for csv uploads.

经过一整个下午的敲打,当我意识到您指定了“处理程序”而不是“服务”有很大区别时,我又回到了这个问题/解决方案。:) 同样对于可以在后面运行这个 jquery 的工作处理程序,我去了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

回答by Dev.Mustafa Alhelo

use this in your web configuration file

在您的网络配置文件中使用它

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

回答by Dave Hogan

$("#file-upload") 

should be

应该

$("#ctl00_PageContent_Signup_ctl06_MWFileUpload_file-Upload")

Look at changing the file-upload control on the server code to have a static server side id by using the ClientIdModeproperty. Like so:

查看通过使用ClientIdMode属性更改服务器代码上的文件上传控件以具有静态服务器端 id 。像这样:

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

Then you can be sure the ID of the control in the client code will be FileUpload1

那么你可以确定客户端代码中控件的ID将是 FileUpload1

回答by omid

You can use this:

你可以使用这个:

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