因此,我有一个表单,要求用户填写一些输入框、文件(eg.docx、pdf等)和图像(eg.jpg、png等)中的文本,然后将所有数据发送到-and代码背后的Webmethod中做一些处理。成功地实现了输入框中的字符串(eg.Title、描述等)使用json/ajax请求。唯一让我陷入困境的是通过json传递的文件并被代码隐藏所接收.如有任何帮助或建议,将不胜感激。
$.ajax({
type: "POST",
url: "insert.aspx/eventCreate",
data: {
'eventImage': eventImage,//here's the image
'eventFile': eventFile, //here's the file
'eventTitle': eventTitle,
'eventDesc': eventDesc,
'eventPlace': eventPlace,
'eventType': eventType,
'eventAttendee': eventAttendee,
'userID': userID
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("Call successfull test");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
[WebMethod(EnableSession = true)]
public static string eventCreate(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string UserID)
{
//how do I get the Image and file from the request??
return "0";
}发布于 2018-10-14 07:04:16
对不起,您刚才注意到您正在使用'WebMethod‘。
您可以将文件作为base64字符串发布,并在WebMethod中接收相同的文件,并将base64转换回WebMethod中的文件。
请按照how-to-convert-file-to-base64-in-javascript链接将文件转换为base64。
以及链接base64-encoded-string-to-file,将base64转换回the方法中的文件。
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
$.ajax({
type: "POST",
url: "insert.aspx/eventCreate",
data: {
'eventImage': eventImage,//here's the image
'eventFile': eventFile, //here's the file
'eventTitle': eventTitle,
'eventDesc': eventDesc,
'eventPlace': eventPlace,
'eventType': eventType,
'eventAttendee': eventAttendee,
'userID': userID,
'fileBase64': getBase64(document.getElementById('fileUploadId').files[0])
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("Call successfull test");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
[WebMethod(EnableSession = true)]
public static string eventCreate(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string UserID, string fileBase64)
{
//how do I get the Image and file from the request??
File.WriteAllBytes(@"c:\yourfile", Convert.FromBase64String(fileBase64));
return "0";
}https://stackoverflow.com/questions/52800066
复制相似问题