首页 > 解决方案 > 如何使用 Ajax 发送输入文本和 FileUploud 数据

问题描述

如何在 asp.net C#(Web Forms) 中使用 Ajax 发送输入文本和 FileUploud?

<input type="text" id="txtChanelName" class="input-field" runat="server" />

<input type="file" id="fpImage" class="input-field" runat="server"  />   

<button id="btnInsertChanel" onclick="return AddChanel(this.value);" 
    value='<%=Session["GroupId"].ToString()%>' >add</button>

我的javascript代码如下

<script>
    function AddChanel(groupId) {
        var chanelname = document.getElementById("txtChanelName");
        var file = document.getElementById("fpImage").files[0];
        $.ajax({
            type: "POST",
            url: "../../Ajax/Chanel.aspx/AddChanel",
            data: "{'chanName':'" + chanelname.Value 
                                  + "','groupId':'" + groupId 
                                  + "','image':'" + file + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //
            },
            error: function (ex) {
                alert("err");
            }
        });
    }
</script>

我的 c# 代码如下

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool AddChanel(string chanName,string groupId, string[] image)
{
    //Breakpoint
    return true;
}

标签: c#asp.netajaxwebforms

解决方案


我将文件转换为 base64 并发送到后面的代码

    var chanelname = document.getElementById("ContentPlaceHolder1_txtChanelName");
        var file = document.getElementById("ContentPlaceHolder1_fpImage").files[0];

    var reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = function () {

        $.ajax({
            type: "POST",
            url: "../../Ajax/Chanel.aspx/AddChanelToGroup",
            data: "{'chanName':'" + chanelname.Value + "','groupId':'" + groupId + "','image':'" + btoa(reader.result) + "','extension':'" + extension + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

            },
            error: function (ex) {
                alert("خطا در ارتباط");
            }
        });

    };
    reader.onerror = function () {
        alert('خطا');
    };

Code behind is below:
 [WebMethod]
    public static int AddChanelToGroup(string chanName, string groupId, string image, string extension)
    {
        byte[] b = Convert.FromBase64String(image);
        File.WriteAllBytes("path....", b);
        return ChanelHelper.AddChanelToGroup(chanName,groupId,image,extension);
    }

推荐阅读