Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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

<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();
                  }
            });
      });
share|improve this question
can you post the HTML generated by <asp:FileUpload ID="FileUpload1" runat="server" CssClass="file-upload-dialog" />. Also, in the console tab, you can type var fileInput = $("#file-upload") and check what value it has – TCHdvlp Jun 14 at 13:22
see my edits please... – patel.milanb Jun 14 at 13:27
it says undefined in the console.. i dont know why – patel.milanb Jun 14 at 13:31
yeah ! you are looking for an element with an id file-upload. There is no element with this id on the generated html. Try DaveHogan tip. – TCHdvlp Jun 14 at 13:37
tried with the solution with no luck... still same error – patel.milanb Jun 14 at 13:40

1 Answer

$("#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 ClientIdMode property. Like so:

<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

share|improve this answer
tried with the id generated in html by coping in jquery.. still no luck.. same error – patel.milanb Jun 14 at 13:39
Well the trick is to use the ClientIDMode to be static so you can ensure the elements client ID matches. (same with the button control). – DaveHogan Jun 14 at 13:41
yeah that's true but i am not able to do that cause it might cause some another issue. BUT i am putting the same id in jquery then why i am getting the error? – patel.milanb Jun 14 at 13:43
Ensure the ID's are definitely matching and confirm the result of var fileInput in your browsers watch / console window. If the ID exists then you will not get an 'undefined'. – DaveHogan Jun 14 at 13:45
i have tried this and still getting undefinded – patel.milanb Jun 14 at 14:37
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.