【发布时间】:2021-01-01 13:24:40
【问题描述】:
有一个客户端在 JavaScript 中发送一个文件对象。 有一个用 Python 编写的服务器。 请查看以下客户端和服务器的代码。
客户端(JavaScript):
function sendFile(file) {
fetch('http://localhost:8088', {
method: 'POST',
body: JSON.stringify({
name: "file",
code: file
})
})
.then(res => {
// handle response
var reader = res.body.getReader();
reader.read()
.then(({done, value}) => {
// need to check done
let chunks = new Uint8Array(value.length);
chunks.set(value, 0);
let result = new TextDecoder("utf-8").decode(chunks);
console.log(result);
});
})
.catch(err => {
// handle error
console.log('fetch error:', err);
});
}
document.getElementById('sendBtn').addEventListener('change',
()=>{this.sendFile(document.getElementById('fileInput').files[0]);});
服务器(Python):
#!/usr/bin/python
import BaseHTTPServer
import json
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.getheader('content-length'))
body = self.rfile.read(length)
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write("post response")
data = json.loads(body)
# print data['file'] just returns '{ }'
# I would like to save this file on sever side.
# Is it possible??
server = BaseHTTPServer.HTTPServer(("localhost", 8088), MyHandler)
server.serve_forever()
我想知道是否有办法在python世界上读取用javascript编写的文件对象。
【问题讨论】:
-
我不清楚这个问题。但是,如果它是 json,您可以使用
import json将 json 直接加载到 python 代码(作为字典)中。见docs.python.org/3/library/json.html -
看来我需要发送文件数据而不是文件。所以 Python 服务器是空的 { }。我找到了stackoverflow.com/questions/24139216/… 现在我需要了解如何将数据保存到 Python 服务器端的文件中。
-
最后我可以用stackoverflow.com/questions/33870538/…保存图像数据
标签: javascript python