Как отправить входной текст и данные FileUploud с помощью Ajax - PullRequest
0 голосов
/ 26 октября 2019

Как отправить входной текст и FileUploud с помощью Ajax в asp.net C # (веб-формы)?

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

Ответы [ 2 ]

1 голос
/ 27 октября 2019

Я конвертирую файл в 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);
    }
0 голосов
/ 26 октября 2019

Несколько вещей, на которые стоит обратить внимание:

  • вместо того, чтобы получать только элемент html с var chanelname = document.getElementById("txtChanelName");, получите значение сразу с помощью var chanelname = document.getElementById("txtChanelName").value;.
  • , если ваша кнопкавызывает обратную передачу, и вы не хотите этого, сделайте первую строку вашего js event.preventDefault();.
  • , вам не нужно return для события onclick кнопки.

Следующие 2 являются, вероятно, наиболее важными:

  • , если вам нужен только 1 файл, сразу получите имя: var file = document.getElementById("fpImage").files[0].name;. Затем измените код для получения string вместо string[].
  • , если вы используете document.getElementById("fpImage").files[0], вы получите object и вам придется изменить код наполучите object, а не string[].
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...