Accessing FormData from ajax to aspx.cs code

42 Views Asked by At

on adding debugger in console I am geting that file is uploaded successfully but debugger is not coming to codebehind or we can say that code behind is not accessable

this is my js file

function uploadFile() {
           debugger
           var fileInput = document.getElementById("myFile");
           var file = fileInput.files[0];

       if (file) {
           var applicationID = selectedApplicationID;
           var orderID = $("#txtOrderID").val();
           var companyID = $("#tdCompanyID").text();
           var orderedDate = $("#tdOrderedDate").text();
           var instaProductName = $("#tdReport").text();

           var data = new FormData();
           data.append("ApplicationID", applicationID);
           data.append("CompanyID", companyID);
           data.append("OrderID", orderID);
           data.append("OrderedDate", orderedDate);
           data.append("ProductName", instaProductName);
           data.append("uploadedFile", file);

           // Make an AJAX request to the server to upload the file
           $.ajax({
               type: "POST",
               url: "InstaReportsDownloader.aspx/UploadFile",
               data: data,
               contentType: false,
               processData: false,
               success: function (response) {
                   // Handle the success response
                   console.log("File uploaded successfully!");
                   console.log(response);
               },
               error: function (xhr, status, error) {
                   // Handle the error response
                   console.log("File upload failed!");
                   console.log(error, status, xhr);
               }
           });
       }
   }

And this is code behind

    [System.Web.Services.WebMethod(EnableSession = true)]
    public  string UploadFile(int ApplicationID, int CompanyID, int OrderID, DateTime OrderedDate, string ProductName, HttpPostedFile uploadedFile)
    {
        string DataDirectory = ConfigurationManager.AppSettings["DataDirectory"].ToString();
        string folderPath = null;

        if (ApplicationID == 4)
        {
            folderPath = Path.Combine(DataDirectory, "XML Reports", CompanyID.ToString(), ProductName);
        }
        else if (ApplicationID == 5)
        {
            folderPath = Path.Combine(DataDirectory, "InstaAPI Reports", CompanyID.ToString(), ProductName);
        }

        // Create the directory if it doesn't exist
        Directory.CreateDirectory(folderPath);

        // Generate the file name based on the OrderedDate
        string fileName = $"Report_{OrderedDate.ToString("mm/dd/yyyy")}.xml";
        string filePath = Path.Combine(folderPath, fileName);

        // Save the uploaded file to the specified path, overwriting if it already exists
        uploadedFile.SaveAs(filePath);

        return filePath;
    }
1

There are 1 best solutions below

1
Albert D. Kallal On

Ok, so keep in mind that when you don't send/setup the data format as xml, or json, and when you add

contentType: false,
processData: false,

Then you NOT REALLY calling a webmethod anymore.

In fact, think of what occurs when you hit a standard button?

Well, the whole page is posted back, including that of formdata().

So, what your example code does in effect is create YOUR own post-back!!!!

And with that format you CAN not, and ARE not, and DO not call a web method anymore.

And the return response will in fact be the web page!!!

So, you have to get/grab/test for "some" value in the form(), and take appropriate action on that fact.

This means you have to use the page load event here.

You WILL find that IsPostBack will be false in this case, since no "standard full submission" of the page will have occurred.

So, that means, you can dump the web method (it will be ignored anyway).

And you do NOT have any parameter's of some web method either. However, you certainly do have formdata which you can get those values.

And I doubt your response is of much use, since you going to get a web page returned to the client side.

So, say this js (client side) code:

        <input id="Button11" type="button" value="ajpost"
            onclick="TestFun();return false"
            />

        <script>

            function TestFun() {

                var myForm = new FormData()
                myForm.append("test", "test")
                myForm.append("FirstName", "Albert")

                $.ajax({
                    type: "POST",
                    url: "AJPostTest.aspx",
                    data: myForm,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        // Handle the success response
                        console.log(response);
                    },
                    error: function (xhr, status, error) {
                        // Handle the error response
                        console.log("File upload failed!");
                        console.log(error, status, xhr);
                    }
                });
            }

        </script>

So, now in page load, you can pick up this information like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Page.Request.Form["test"] != null) 
            {
                // we have "test", so that's our ajax post call
                Debug.Print("Name passed = " + Page.Request.Form["FirstName"].ToString());
            }
        }
    }

Output:

enter image description here

So, that type of code in effect creates YOUR own custom page post-back, and it not at all a webmethod call.

You will have to process that data and your posted data in the page on-load event.