c# - 如何使用 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;
}
解决方案
我将文件转换为 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);
}
推荐阅读
- algorithm - 关于循环算法的进程和队列的理解问题
- java - 如何使用多个数据源进行故障转移 rdbms
- python - 使networkx情节看起来不错
- excel - 如何修复 Power BI 中类型更改的错误?
- html - CSS滚动阴影没有出现在背景颜色之上
- java - 如何在 switch 语句中使用字符串作为 case 标签
- json - 如何在 Gulp 中创建 Watch 以在 JSON 文件更改时进行更新
- winapi - MFC/GDI CRgn CreateEllipticRgn 短两个像素?
- javascript - HTML / Javascript 文件夹选择器
- google-bigquery - BigQuery - 将整数作为时间戳提取到表中