使用jquery ajax在同一POST请求中上传文件和JSON数据? [英] Upload file and JSON data in the same POST request using jquery ajax?

查看:98
本文介绍了使用jquery ajax在同一POST请求中上传文件和JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery Ajax发送POST请求,我想在其中上传文件和一些json数据.请找到代码,

I am trying to send a POST request using jQuery Ajax, where I would like to upload a file and some json data. Please find code,

var logoImg = $('input[name="logoImg"]').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);

var objArr = [];
objArr.push({
  "id": id,
  "name": userName
});

var obj = [{
  "objArr": objArr,
  "formData": formData
}];

$.ajax({
  type: "POST",
  url: url,
  dataType: "json",
  data: JSON.stringify(obj),
  contentType: "application/json",
  cache: false,
  async: false,
  complete: function(data) {
    alert("success");
  }
});

但是我收到内部服务器错误:500 ,并且未调用后端API.

But I am getting Internal server error: 500 and the backend API is not called.

请帮助我在同一AJAX请求中发送文件和数组obj.预先感谢

Please help me to send a file and an array obj in same AJAX request. Thanks in advance

推荐答案

您无法序列化在请求中发送的任何二进制数据.

You cannot serialise any binary data you send in the request.

要使用 FormData 对象发送其他信息,只需使用 append()方法添加它,类似于图像本身:

To send additional information with the FormData object, just use the append() method to add it, similar to how you are with the image itself:

var logoImg = $('input[name="logoImg"]').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);
formData.append('id', id);
formData.append('name', userName);

$.ajax({
  type: "POST",
  url: url,
  data: formData,
  contentType: false,
  processData: false,
  cache: false,
  complete: function(data) {
    alert("success");
  }
});

请注意,选项中的重要部分是将 contentType processData 设置为 false ,并删除 async:false ,以使请求异步发生.

Note the important parts in the options are setting contentType and processData to false, and removing async: false so that the request occurs asynchronously.

最后,请注意,如果您要在请求中发送的输入全部包含在同一表单中,则可以使用 FormData 构造函数将代码简化为:

Finally, note that if the inputs you want to send in the request are all contained within the same form you can use the FormData constructor to simplify your code to just:

var formData = new FormData($('#yourForm')[0]);

这篇关于使用jquery ajax在同一POST请求中上传文件和JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆