【问题标题】:Sending a file in jquery ajax POST Api call在 jquery ajax POST Api 调用中发送文件
【发布时间】:2019-03-28 16:24:43
【问题描述】:

使用 Jquery,当我尝试通过发送任何文件来调用外部 API 时。我面临 415 Unsupported Media Type 错误。我正在尝试使用 FormData() 和 beforeSend() 函数中的标题数据发送我的文档。建议我发送数据的正确方式。

<div id="folder-browser">
  <input type="file" id="file-select" name="photos" />
  <button id="myButton" value="click me">click me</button>
</div>
$("#myButton").click(function() {
  var myData = new FormData();
  var myFile = document.getElementById("file-select");
  myData.append(myFile.files[0].name, myFile.files[0]);

  $.ajax({
    url: 'http://10.96.45.179/RightFax/API/attachments',
    data: myData,
    processData: false,
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Authorization', 'Basic c3lzYWRtaW46cGFzc3dvcmQtMQ==');
    },
    type: 'POST',
    success: function(result) {
      console.log(result);
       return result;
    }
  });
});

查询 2:如果我的文档存在于 URL 中。请告诉我如何将 URL 作为文件源传递。 例如:

filepath = 'http://seekvectorlogo.com/wp-content/uploads/2018/02/opentext-vector-logo-small.png';

我需要将此文件源传递给我的外部 API。

【问题讨论】:

  • FormData对象中上传二进制数据时需要设置contentType: false
  • 谢谢!它解决了我的错误。
  • 很高兴它有帮助。我在下面添加了它作为您的答案

标签: javascript jquery


【解决方案1】:

在FormData对象中上传二进制数据时需要设置contentType: false:

$.ajax({
  url: 'http://10.96.45.179/RightFax/API/attachments',
  data: myData,
  processData: false,
  contentType: false,
  // your other settings...
});

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多