Home > OS >  ASP.NET Send a file from Javascript File upload to WebMethod in C#
ASP.NET Send a file from Javascript File upload to WebMethod in C#

Time:11-01

While there are similar other posts, none of them are actually focused on ASP.NET Websites with a Javascript PageMethod file upload. I would like to select a file from my file selector (it's working) and send that to the WebMethod to upload it.

I have managed to select the file and send it to my WebMethod. However, I am not sure how to convert the object to a readable format in C#. It's a CSV File.

Javascript:

      <script>
            //formstone file drop picker library
            $(".upload").upload({
                beforeSend: onBeforeSend
            });

            function onBeforeSend(formData, file) {
                if (file.name.indexOf(".csv") < 0) {
                    return false;
                }

                //file is successfully received here
                var fd = new FormData();
                fd.append(file.name, file);
    
                //this gets called as well
                PageMethods.set_path("manage-products.aspx");
                PageMethods.UploadCSV(file, onSuccess, onFailure);

                function onSuccess(response) {
                }

                function onFailure() {
                    console.log("FAIL");
                }

                return formData;
            }
      </script>

C# WebMethod:

[WebMethod]
public static void UploadCSV(object formData)
{ 
    //I'm trying to get the file data and convert to a readable file here
}

CodePudding user response:

This Question is Already Answered here i feel. There are several ways to accept a file in a c# controller:

One of them is like this:

[APIController]
[HttpPost]
public ActionResult Post(IFormFile myFile)
{
if(myFile==null)
{//ErrorHandling
 return BadRequest();
}
//do what ever you please with your file here
return Ok();
}

The Example above was the easiest way for me to understand and implement. maybe its useful to you. Just Open Swagger on this controller press F12 in your Browser and use the Endpoint. you will see in Network Section of your Browser dev tools how the Request to the Controller should be Implemented.

  • Related