ajax发送图片flask接收
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示并发送图片</title>
</head>
<body>
<input type="file" id="file-ip-1" accept="image/*" onchange="showPreview(event);">
<button>上传</button>
<div id="result">
</div>
<div class="preview">
<img id="file-ip-1-preview">
</div>
<script type="text/javascript">
let result
let input = document.getElementsByTagName('input')[0]
const btns = document.querySelectorAll("button")
const formData = new FormData()
input.oninput = (e) => {
let file = e.target.files[0]
var src = URL.createObjectURL(file)
var preview = document.getElementById("file-ip-1-preview")
preview.src = src
preview.style.display = "block"
formData.append("file", file)
}
btns[0].onclick = function () {
let x = new XMLHttpRequest()
x.open("POST", "/api/image1")
x.send(formData)
}
</script>
</body>
</html>
后端代码
@app.route("/image1", methods=['POST'])
def upload_image1():
a = request.files["file"]
print(a.filename)
print(type(a.read()))
return "hello world"
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5000)
注意nginx配制,否则有跨域问题