2013-06-14 20 views
6

Sto provando a farlo funzionare, ma sto ricevendo un errore durante il caricamento del file.caricamento file utilizzando jquery ajax e gestore di asp.net

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

errore

enter image description here

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

modifiche

Infine, ho ottenuto che funziona facendo queste cose per formare i dati

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

PIENA DI LAVORO CODICE

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

puoi pubblicare il codice HTML generato da ' '. Inoltre, nella scheda della console, puoi digitare 'var fileInput = $ (" # file-upload ")' e controlla quale valore ha – TCHdvlp

+0

vedi le mie modifiche per favore ... –

+0

dice undefined nella console .. non so perchè –

risposta

1
$("#file-upload") 

dovrebbe essere

$("#ctl00_PageContent_Signup_ctl06_MWFileUpload_file-Upload") 

Guardate modificare il controllo di caricamento file sul codice del server per avere una statica lato server id utilizzando la proprietà ClientIdMode. In questo modo:

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

Poi si può essere sicuri che l'ID del controllo nel codice client sarà FileUpload1

+0

provato con l'id generato in html coping in jquery ..ancora senza fortuna .. stesso errore –

+0

Bene, il trucco è usare la ClientIDMode per essere statici in modo da poter garantire che gli elementi ID del client corrispondano. (lo stesso con il controllo pulsante). – DaveHogan

+0

sì è vero ma non sono in grado di farlo perché potrebbe causare qualche altro problema. MA sto mettendo lo stesso id in jQuery, allora perché sto ricevendo l'errore? –

2

Dopo un intero pomeriggio di sbattere, sono tornato a questa domanda/soluzione quando mi sono reso conto che avevi specificato "gestore" piuttosto che "servizio" grande differenza. :) Anche per un hander funzionante in grado di eseguire questo jquery nella parte posteriore sono andato a https://github.com/superquinho/jQuery-File-Upload-ASPnet e ho rifilato ciò di cui non avevo bisogno. Ecco il codice del gestore che sto usando (VS2012). Come puoi vedere, lo utilizzo solo ora per i caricamenti 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 
1

uso questo nel tuo web file di configurazione

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

0

È possibile utilizzare questo:

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

ohh, grazie omid.its molto bene, il suo funzionamento, ye hoo – omid

Problemi correlati