javascript - 当“contentType”为“false”时,使用 Ajax 从 Web 服务返回 JSON 而不是 XML
问题描述
我进行了 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);
}
});
和网络服务方法:
[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);
}
解决方案
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);
}
});
在服务器端,使用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);
}
这应该允许响应为所需的类型
推荐阅读
- ios - 自定义表格单元格中的堆栈视图
- validation - 如何在 TYPO3 FlexForms 中进行评估并防止保存无效输入
- r - 将绘图分配给循环中的变量
- sql - 如何将不同年份同一月份的数据分开?
- elasticsearch - 我们如何使用 elasticsearch 来处理时间序列数据?我想将 Elastic-Stack 作为一个整体用于时间序列数据
- python - ProcessPoolExecutor:进程池中的一个进程在future正在运行或挂起时突然终止
- python - Flask socket IO 从另一个模块发出
- assembly - 汇编(64 位) - 将 NUL 移动到 byte[rax] 以进行“比较”
- javascript - 在单元测试中覆盖注入令牌
- ios - 如何增加 UITableView 中自定义单元格的宽度