如何使用 Falcon Python 保存来自 POST 请求的图像

How to save an image from POST request with Falcon Python

我正在尝试找到一种方法来保存我从 POST 请求中获得的图像,到目前为止,我找到的所有解决方案最终都无法正常工作,例如 this

上面解决的问题是我只是超时错误

我现在试着稍微更改一下代码,但还是不行,你能帮我吗?

    def on_post(self, req, resp):
        """Handles Login POST requests"""
        json_data = json.loads(req.bounded_stream.read().decode('utf8'))
        base64encoded_image = json_data['image_data']
        with open('pic.png', "wb") as fh:
            fh.write(b64decode(base64encoded_image))

        resp.status = falcon.HTTP_203
        resp.body = json.dumps({'status': 1, 'message': 'success'})

我得到的错误是"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"

在您的 Falcon 后端

尝试falcon-multipart

pip3 install falcon-multipart

然后将其作为您的中间件包含在内。

from falcon_multipart.middleware import MultipartMiddleware

api = falcon.API(middleware=[MultipartMiddleware()])

这将解析任何 multipart/form-data 传入请求,并将键放入 req._params 中,包括文件,因此您可以将字段作为其他参数获取。

# your image directory
refimages_path = "/my-img-dir"

# get incoming file
incoming_file = req.get_param("file")

# create imgid
imgId = str(int(datetime.datetime.now().timestamp() * 1000))

# build filename
filename = imgId + "." + incoming_file.filename.split(".")[-1]

# create a file path
file_path = refimages_path + "/" + filename

# write to a temporary file to prevent incomplete files from being used
temp_file_path = file_path + "~"
with open(temp_file_path, "wb") as f:
    f.write(incoming_file.file.read())

# file has been fully saved to disk move it into place
os.rename(temp_file_path, file_path)

在您的前端

在请求 header 中发送 Content-Type: multipart/form-data;。也不要忘记提供 boundary 因为在 RFC2046:

中指定

The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line
consisting entirely of two hyphen characters ("-", decimal value 45)
followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.