我正在使用 Summernote,我想将图像上传到我的网络服务器。下面是我正在使用的代码
默认.aspx
<script type="text/javascript">
$(document).ready(function () {
$('#summernote').summernote({
onImageUpload: function (files, editor, $editable) {
alert('image?');
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({
url: "Default.aspx/UploadImage",
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success: function (imageUrl) {
alert(imageUrl);
if (!imageUrl) {
// handle error
return;
}
editor.insertImage($editable, imageUrl);
},
error: function () {
alert('error');
// handle error
}
});
console.log('image upload:', files, editor, $editable);
}
});
});
</script>
默认.asp.cs
[System.Web.Services.WebMethod]
public static string UploadImage(HttpPostedFileBase file)
{
//Saving to Server
return imageUrl;
}
但它没有调用服务器端函数。另外,alert(imageUrl) 为我提供了完整的页面 html。
我哪里错了?
使用网络信息更新问题(谷歌浏览器)
编辑2
根据建议更新
代码:
url: "About.aspx/UploadImage",
data: "multipart/form-data",
type: 'POST',
cache: false,
contentType: "application/json",
错误:
注意:我已将页面从 Default.aspx 更改为 about.aspx(但代码相同)
最佳答案
WebMethod
或“页面方法”expect contentType: "application/json;
附加引用:Scott Guthrie - JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks :
There is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json. It this content type header is not sent, ASP.NET AJAX will reject the request on the server.
- 这就是为什么您的
警报
返回页面(html),您的调用成功调用页面
(default.aspx),但是webmethod
未调用。
参见this for direction/possible solution .
我认为你感到困惑,可能是我的错。我会尝试简化:
- 链接中的建议是不要使用 WebMethod。
- 为了发送文件,您的
contentType
必须是multipart/form-data
- 查看相关问题:jquery contentType false
- 但如上所述,WebMethods 要求
contentType
为application/json
- 它不适用于 WebMethods(因此该链接建议使用通用处理程序)。
第...
关于jquery - 无法调用服务器端 webmethod 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530098/