如何使我的HTTP请求与表单相同

问题描述 投票:1回答:1

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

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

在瓶子的网站上有一个表格的例子: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>

在瓶子里我有:

@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>

我已经检查过网络中的开发人员工具,并且请求似乎与表单发送的请求相同,但是瓶子找不到该文件。

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

任何帮助将不胜感激!

javascript python file-upload xmlhttprequest bottle
1个回答
1
投票

您的JavaScript代码似乎很好,除了您使用xhr.setRequestHeader设置请求标头的位置。 FormData为您处理多部分编码,您不需要手动设置请求标头。我刚刚尝试过,它似乎与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);
}
© www.soinside.com 2019 - 2024. All rights reserved.