我进行了 AJAX 调用以将图像文件发送到我的网络服务 (.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);
}
});
和网络服务方法:
[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);
}
最佳答案
在发出期望 JSON 的请求时设置 Accept
header
$.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);
}
});
在服务器端,使用 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);
}
这应该允许响应是所需的类型
关于javascript - 使用 Ajax 从 Web 服务返回 JSON 而不是 XML 而 'contentType' 是 'false',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074089/