【问题标题】:How to post webform with file to webmethod using Jquery/Ajax?如何使用 Jquery/Ajax 将带有文件的 webform 发布到 webmethod?
【发布时间】:2015-07-25 20:11:55
【问题描述】:

这甚至可能吗?我有一个带有某些文本框等的网络表单和一个文件上传元素。我正在尝试使用 .ajax() 方法将数据发送到 webmethod。 在我看来,无法以这种方式将文件内容发送到 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";
}

几个小时以来,我一直在努力寻找解决方案。似乎没有人能够帮助我解决这个问题。这甚至可能使用这种方法。如果不是,我该怎么做?有人建议我应该尝试提交整个表单而不是传递单个值。

【问题讨论】:

  • 尝试使用Json stringify向服务发送数据
  • @dazzlingkumar Jsonstringify 发送文件?
  • 是的,以 Json 格式发送到服务,然后它会命中服务
  • @Arbaaz 你想在 webmthod 中发送文件名吗?
  • @MairajAhmad 我想自己发送文件。

标签: javascript jquery asp.net ajax webforms


【解决方案1】:

这可以在没有任何库的情况下使用JavaScript FileReader API 来完成。有了它,modern browsers 可以在用户选择文件后使用 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);
    }
  });

}
<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调用中的参数)。

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

【讨论】:

  • 抱歉回复晚了。我收到TypeError: document.getElementById(...) is null
  • 你在哪里得到这个错误?你能分享你的代码吗?
  • 这里:document.getElementById("myFile").addEventListener("change", function(e) { var selectedFile = document.getElementById('myFile').files[0]; reader.readAsText(selectedFile); })
  • input type="file" 的 id 是什么?
  • 您将该代码放在页面的什么位置?
【解决方案2】:

首先进入App_Start>>RouteConfig.cs>>settings.AutoRedirectMode = RedirectMode.Off;然后用我的代码替换你的函数它肯定会为你工作, 祝你好运..

function Submit() {
    $.ajax({
        type: "POST",
        url: "UploadImage.aspx/RegisterSupplier",
        data: "{'file' : " + JSON.stringify(document.getElementById("myFile").value) + ",'biddername':" + JSON.stringify(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);
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2017-07-03
    • 2016-06-13
    • 2011-04-01
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多