【发布时间】:2024-05-20 02:55:02
【问题描述】:
我需要一些关于我的 HTTP 请求的帮助。这是设置:
- 网页将图像加载到表单并将其发送到运行瓶子的 python 服务器(使用表单或自定义 http 请求)
- 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') 返回 None 和 file = request.files 返回 <bottle.FormsDict object at 0x7ff437abf400> 所以有些东西,但我不明白如何访问它!
任何帮助将不胜感激!
【问题讨论】:
标签: javascript python file-upload xmlhttprequest bottle