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

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

问题描述

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

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读取文件的内容,然后您可以按照自己的方式进行操作(将其编码为字符串,然后将其发送到服务器).

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天全站免登陆