【问题标题】:Sending file in post request在 post 请求中发送文件
【发布时间】:2019-01-13 07:07:18
【问题描述】:

在 python 中,我发送这样的文件:

with open('D:\\someimage.jpg', 'rb') as image:
imager = image.read()
files = {'image': imager}
r = requests.post(url, files=files)

我想在 js 中做类似的事情,但我总是收到 400 Bad Request 错误。我认为问题在于我不知道文件应该具有什么类型。我尝试以初始“文件”类型,作为数组缓冲区,作为二进制字符串传递它 - 没有任何效果。这是我的代码:

var reader = new FileReader();
reader.readAsArrayBuffer(aFiles[0]);
reader.onload = function () {
var arrayBuffer = this.result,
array = new Uint8Array(arrayBuffer),
binaryString = String.fromCharCode.apply(null, array);
jQuery.ajax({
    url: '/streamer', 
    method: 'POST',
    files: {'image': binaryString},
    success: function(response) {
        alert(response);
    },
    error: function(xhr, status, error) {
       alert(JSON.parse(xhr.responseText));
    }});

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

如果您需要发送更多字段,可以将文件作为 FormData (multipart/form-data) 发送,如果您只想直接发送二进制文件,则可以作为 Blob 发送。

jQuery 在处理您发送的数据方面尝试变得聪明。但是 jQuery 不理解 FormData 或 blob,它将它视为一个对象并做错事。这就是为什么你需要设置 processData = false 并且不要通过 contentType = false 设置错误的请求内容类型,让 xhr 自己做。

var fd = new FormData();
fd.append('image', aFiles[0] /*, optional filename */)

var req = jQuery.ajax({
  url: '/streamer', 
  method: 'POST',
  data: fd, // sends fields with filename mimetype etc
  // data: aFiles[0], // optional just sends the binary
  processData: false, // don't let jquery process the data
  contentType: false // let xhr set the content type
});

// jQuery is promise A++ compatible and is the todays norms of doing things 
req.then(function(response) {
  console.log(response)
}, function(xhr) {
  console.error('failed to fetch xhr', xhr)
})

但是,如果您只支持具有fetch api 的最新浏览器,则您实际上并不需要 jQuery

var req = fetch('/streamer', {
  method: 'post',
  body: fd /* or aFile[0]*/
}); // returns a promise

req.then(function(response) {
  // returns status + response headers
  // but not yet the body, 
  // for that call `response[text() || json() || arrayBuffer()]` <-- also promise

  if (res.ok) {
    // status code was 200-299
  } else {
    // status was something else
  }
}, function(error) {
  console.error('failed due to network error or cross domain')
})

【讨论】:

  • 感谢您的回答,但我仍然收到 400 错误... Postman 中的请求如下所示:link
  • 哦,我忘记了获取示例中的method: post。可能就是这样,刚刚编辑过
  • 我尝试使用您的第一个示例中的 ajax 调用。不知道有什么问题
  • hmm,试着在你的开发者工具中查看请求头,看看有什么不同
  • 通过获取示例我得到“状态是别的东西”
猜你喜欢
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多