首页 > 解决方案 > 发布请求缺少边界标头

问题描述

我正在尝试将csv文件发送到服务器。我FileReaderAPI用来加载文件,然后通过ajax. 但我收到以下错误。

对于请求 'POST /api/upload' [缺少边界标头]

JS

$('#upload-file-btn').on('click', function(e){
      e.preventDefault();

      var file = document.getElementById('input_file').files[0];
      console.log(file);
      reader = new FileReader();
      reader.onload = function () {
          var source = reader.result;
          var payload = {source: source};
          console.log(source);
          $.ajax({
           url:"http://localhost:9000/api/upload",
           type:"POST",
           data: JSON.stringify(payload),
           success: function(data){
              console.log(data);
           }
         });

      }
      reader.readAsText(file);
});

一些解决方案建议"Content-Type" : "multipart/form-data"手动包含标题会导致问题。我没有使用但仍然遇到上述问题。

标签: javascriptajaxhtmlpost

解决方案


如果您需要将数据作为文件发送,则必须使用 FormData 对象通过 ajax 发送多部分/表单数据数据。

     var fd = new FormData();
     fd.append('source', $('#input_file')[0].files[0]);
     $.ajax({
       url:"http://localhost:9000/api/upload",
       type:"POST",
       data: fd,
       contentType: false,
       processData: false,
       success: function(data){
          console.log(data);
       }
     });

推荐阅读