jquery 通过API发送文件[重复]

jdgnovmf  于 2023-02-03  发布在  jQuery
关注(0)|答案(1)|浏览(110)
    • 此问题在此处已有答案**:

How can I upload files asynchronously with jQuery?(34个答案)
5小时前关门了。
我正在尝试将带有jsonData的Fileobjet发布到Ajax发布

将fileobject和jsonData追加到formData中,然后通过API发送。
我不知道下面的脚本将工作与否...可以任何人都可以帮助这个。
获取错误,
1.文件为空{}

  1. 401错误提示
    输入
<input
  type="file"
  id="mypicid"
  name="file"
  accept="application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,text/plain, application/pdf, image/\*" 
  required
  style="word-wrap: break-word; width: 99%"
/>

JavaScript语言

$("form#data").submit(function (e) {
  e.preventDefault();
  var formData = new FormData(this);
  var datajson_obj = {
    file: formData,
    jsonData: {
      uploadImmunizationReport: {
        userId: user_ids,
        provider_name: "",
        documentType: "IMMUNIZATION",
        documentName: savefile_name,
        memberId: memberids,
        documentDateAndTime: "2023-02-01T10:09:17.000+0000",
        lab_name: "",
      },
    },
  };
  var datajson_data = JSON.stringify(datajson_obj);
  $.ajax({
    url: "xxxxxxx", //URL From API
    data: datajson_data,
    crossDomain: true,
    dataType: "json",
    type: "POST",
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Credentials": "true",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "*",
      Authorization: "Bearer" + token,
    },
    success: function (response) {
      $("#mydiv").css("display", "none");
      location.reload();
    },
  });
});
9udxz4iz

9udxz4iz1#

定义内容类型: AJAX 请求中的“多部分/表单数据”:-

$.ajax({
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    type    :"POST",
    url     :url,
    dataType:"JSON",
    contentType: 'multipart/form-data',
    data    :$('form').serialize(),
    success :function(response)
    {
      alert('Success');
    }
});

相关问题