javascript - 如何使我的 HTTP 请求与表单的行为相同

标签 javascript python file-upload xmlhttprequest bottle

我的 HTTP 请求需要一些帮助。这是设置:

  1. 网页将图像加载到表单并将其发送到运行 bottle 的 python 服务器(使用表单或自定义 http 请求)
  2. Bottle 接收文件,将其作为 python 脚本的输入,接收结果并将其返回到网页

在 bottle 的网站上,有一个表格示例:https://bottlepy.org/docs/dev/tutorial.html#file-uploads我已经试过了,它有效。这是我使用的代码:

<html>
  <head>
  </head>   
  <body>
    <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
      Select a file: <input type="file" name="upload"/>
      <input type="submit" value="Start upload" />
    </form>
  </body>     
</html>

我在 Bottle 里有:

@route('/solve', method='POST')
def solve():
    file     = request.files.get('upload')
    name, ext = os.path.splitext(file.filename)
    if ext not in ('.png','.jpg','.jpeg'):
        return 'File extension not allowed.'
    print(file.name)
    resolved = sudoku.solve(file.file)
    return str(resolved)

这“有效”,但表单将我重定向到 localhost:8080,这不是我想要的。我尝试将目标放入隐藏的 iFrame,这会阻止重定向,但我无法访问 iFrame 主体中的结果...

我想要的是:发出类似于表单发出的 HTTP 请求。所以我尝试了:

<html>

<head> </head>

<body>
  <form enctype="multipart/form-data" norm="form" id="myForm">
    Select a file:
    <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
    <input type="submit" value="Start upload" />
    <label class="button-upload" onclick="send()">Upload</label>
  </form>

</body>
<script>
  var _file = null;

  function send() {
    var file = document.getElementById("fileInput").files[0]
    console.log(file)
    var url = "http://localhost:8080/solve";

    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader(
      "Content-Type",
      "multipart/form-data; boundary=---------------------------169461201884497922237853436"
    );
    var formData = new FormData();

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
      }
    };
    formData.append("upload", file);
    xhr.send(formData);
  }
</script>

</html>

我用网络中的开发者工具检查过,请求似乎与表单发送的请求相同,但 bottle 找不到该文件。

file = request.files.get('upload')返回 Nonefile = request.files返回 <bottle.FormsDict object at 0x7ff437abf400>所以有一些东西,但我不知道如何访问它!

任何帮助将不胜感激!

最佳答案

您的 JavaScript 代码看起来不错,除了您使用 xhr.setRequestHeader 设置请求 header 的地方。 FormData为您处理多部分编码,您无需手动设置请求 header 。我刚刚试过了,它似乎可以很好地与 bottlepy 搭配使用。

总体而言,如下更改您的 send() 函数:

function send() {
  var file = document.getElementById("fileInput").files[0]
  console.log(file)
  var url = "http://localhost:8080/solve";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  var formData = new FormData();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      alert(xhr.responseText);
    }
  };
  formData.append("upload", file);
  xhr.send(formData);
}

关于javascript - 如何使我的 HTTP 请求与表单的行为相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324087/

相关文章:

javascript - Firebase - 'pushWithPriority' - 和验证

python - exec() 方法的变量在哪里定义?

python - 使用 Hyperopt-TypeError : 'generator' object has no attribute '__getitem__' 进行 XGboost 调整时出现问题

node.js - 通过nodejs和express使用 "vaadin file upload"( polymer )时出错

asp.net-mvc-3 - .net MVC 3.0 带进度条的文件上传

javascript - contentEditable div 中的复选框列表

javascript - appendChild 为空 | javascript/html

javascript - 计算 Javascript 中具有特殊字符的字符串的长度

Python difflib.get_close_matches 搜索字典值 - 如何返回 key ?

asp.net - FileUpload - RequiredFieldValidator 和 RegularExpressionValidator 不触发