如何使用Jquery/Ajax将带有文件的webform发布到webmethod?

Sam*_*ack 5 javascript asp.net ajax jquery webforms

这甚至可能吗?我有一个带有某些文本框等的webform和一个文件上传元素.我正在尝试使用.ajax()方法将数据发送到webmethod .在我看来,不可能以这种方式将文件内容发送到web方法.我甚至都无法点击网络方法.

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>
Run Code Online (Sandbox Code Playgroud)

HTML:

<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
Run Code Online (Sandbox Code Playgroud)

代码背后:

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

  return "a";
}
Run Code Online (Sandbox Code Playgroud)

我一直试图找到解决方案好几个小时了.似乎没有人能帮助我解决这个问题.这甚至可以使用这个approch.如果不是我该怎么办?有人建议我应该尝试提交整个表单而不是传递单个值.

Alv*_*oro 4

这可以通过使用JavaScript FileReader API来完成,无需任何库。有了它,一旦用户选择了文件,现代浏览器就可以使用 JavaScript 读取文件的内容,然后您就可以像以前一样继续操作(将其编码为字符串,并将其发送到服务器)。

代码如下(参考上面的代码):

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

}
Run Code Online (Sandbox Code Playgroud)
<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">
Run Code Online (Sandbox Code Playgroud)

您可以运行上面的代码,选择一个文件(使用纯文本文件进行测试,以便其可读),然后检查控制台以查看其内容。那么其余的代码将是相同的(我做了一些轻微的更改以修复 AJAX 调用中的参数)。

请注意,像这样发送文件有限制:如果您使用 GET 方法,您将有一个较短的参数大小限制,而使用 POST 它将取决于服务器设置......但我猜您甚至有这些限制一份文件。