Ami*_*adi 4 javascript asp.net ajax jquery web-services
我进行了 AJAX 调用,将图像文件发送到我的 Web 服务 (.asmx) 方法之一。一切都很好,但问题是 Web 服务返回 XML 而不是 JSON,因为我必须设置为'contentType'' false',否则文件无法发送。(如果我设置contentType为application/json; charset=utf-8,它会返回 JSON,但我不能这样做,因为我正在发送一个文件。)
这是我的 JavaScript:
function setAvatar(imageFile, successCallback) {
var formData = new FormData();
formData.append("UploadedAvatar", imageFile);
$.ajax({
type: "POST",
url: "/Services/UserService.asmx/SetAvatar",
contentType: false,
processData: false,
dataType: 'json',
data: formData,
success: function (result) {
alert(result.d);
alert(result.d.IsSuccessful);
if (typeof successCallback === 'function')
successCallback(result);
}
});
Run Code Online (Sandbox Code Playgroud)
以及网络服务方法:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result SetAvatar()
{
HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
Image avatar = Image.FromStream(postedFile.InputStream, true, true);
avatar = new Bitmap(avatar, new Size(150, 150));
avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
return new Result(true, Messages.AvatarSavedSuccessfully);
}
Run Code Online (Sandbox Code Playgroud)
发出请求时设置Accept期望 JSON 的标头
$.ajax({
type: "POST",
url: "/Services/UserService.asmx/SetAvatar",
headers: { //SET ACCEPT HEADER
Accept : "application/json; charset=utf-8",
},
contentType: false,
processData: false,
dataType: 'json',
data: formData,
success: function (result) {
alert(result.d);
alert(result.d.IsSuccessful);
if (typeof successCallback === 'function')
successCallback(result);
}
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,使用Json.Net可以序列化结果
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SetAvatar() {
HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
Image avatar = Image.FromStream(postedFile.InputStream, true, true);
avatar = new Bitmap(avatar, new Size(150, 150));
avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
var result = new Result(true, Messages.AvatarSavedSuccessfully);
return JsonConvert.SerializeObject(result);
}
Run Code Online (Sandbox Code Playgroud)
这应该允许响应为所需的类型
| 归档时间: |
|
| 查看次数: |
2766 次 |
| 最近记录: |