Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post webform with file to webmethod using Jquery/Ajax?

Is this even possible? I have a webform with certain textboxes etc and a file upload element. I am trying to send the data to webmethod using .ajax() method. It seems to me that it is not possible to send file content to the webmethod in this manner. I am not even able to hit the webmethod.

script type="text/javascript">
    var btn;
    var span;
    $(document).ready(function (e) {

        $('#btnsave').on('click', function (event) {

            Submit();
            event.preventDefault();
        });
    })

    function Submit() {

        $.ajax({
            type: "POST",
            url: "SupplierMst.aspx/RegisterSupplier",
            data: "{'file' : " + btoa(document.getElementById("myFile").value) + ",'biddername':" + document.getElementById("txtsuppliername").value + "}",
            async: true,
            contentType: "application/json; charset=utf-8",
            success: function (data, status) {
                console.log("CallWM");
                alert(data.d);
            },
            failure: function (data) {
                alert(data.d);
            },
            error: function (data) {
                alert(data.d);
            }
        });

    }
    </script>

HTML:

<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">

Code behind :

[WebMethod]
public static string RegisterSupplier(string file, string biddername)
{
  // break point not hit

  return "a";
}

I have been trying to find solution to this for hours now. Nobody seems to be able help me out on this. Is this even possible using this approch. If not how do I do it? Somebody suggested that I should try to submit entire form instead of passing individual values.

like image 655
SamuraiJack Avatar asked May 14 '15 09:05

SamuraiJack


1 Answers

This can be done without any library, by using the JavaScript FileReader API. With it, modern browsers can read the content of the file using JavaScript once it has been selected by the user, and then you could proceed as you were doing (encoding it as a string, and sending it over to the server).

The code would be like this (using the one above as a reference):

// NEW CODE
// set up the FileReader and the variable that will hold the file's content
var reader = new FileReader();
var fileContent = "";

// when the file is passed to the FileReader, store its content in a variable
reader.onload = function(e) {
  fileContent = reader.result;
  
  // for testing purposes, show content of the file on console
  console.log("The file content is: " + fileContent);
}

// Read the content of the file each time that the user selects one
document.getElementById("myFile").addEventListener("change", function(e) {
  var selectedFile = document.getElementById('myFile').files[0];
  reader.readAsText(selectedFile);
})
// END NEW CODE

var btn;
var span;

$(document).ready(function (e) {
  $('#btnsave').on('click', function (event) {
    Submit();
    event.preventDefault();
  });
})

function Submit() {

  $.ajax({
    type: "POST",
    url: "SupplierMst.aspx/RegisterSupplier",
    // changed this line too!
    data: {
              'file': btoa(fileContent), 
              'biddername': document.getElementById("txtsuppliername").value 
          },
    async: true,
    contentType: "application/json; charset=utf-8",
    success: function (data, status) {
      console.log("CallWM");
      alert(data.d);
    },
    failure: function (data) {
      alert(data.d);
    },
    error: function (data) {
      alert(data.d);
    }
  });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">

You can run the code above, select a file (use a plain text file for testing so it's readable), and check the console to see its content. Then the rest of the code would be the same (I made a slight change to fix the parameters in the AJAX call).

Notice that sending the file like this has limits: if you use the GET method, you'll have a shorter parameter size limit, and with POST it will depend on the server settings... but I guess that you had those limits even for a file.

like image 70
Alvaro Montoro Avatar answered Oct 20 '22 09:10

Alvaro Montoro