如何使用 Jquery/Ajax 将带有文件的 webform 发布到 webmethod? [英] How to post webform with file to webmethod using Jquery/Ajax?

查看:30
本文介绍了如何使用 Jquery/Ajax 将带有文件的 webform 发布到 webmethod?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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">

背后的代码:

[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.

推荐答案

这可以在没有任何库的情况下完成,通过使用 JavaScript FileReader API.有了它,现代浏览器可以在用户选择文件后使用 JavaScript 读取文件的内容,然后您就可以继续执行操作(将其编码为字符串,然后将其发送到服务器).

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">

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

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).

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

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.

这篇关于如何使用 Jquery/Ajax 将带有文件的 webform 发布到 webmethod?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆