Robyn icon indicating copy to clipboard operation
Robyn copied to clipboard

Use post to upload images and keys, request.body cannot get the value of the key

Open cbc123 opened this issue 1 year ago • 2 comments

Bug Description

Use post's multipart/form-data to upload images. The file in the body represents the image to be uploaded, the key, and the field data that the backend needs to get. The result is that request.body cannot get the key data, only the byte array of image data.

Steps to Reproduce

  1. @api.post("/upload") async def file_upload(request:Request): """ 开始上传文件 :return: """ body = request.body

    print(body) byte_array = bytearray(body)

    将字节数组转换为图像

    image = Image.open(io.BytesIO(byte_array)) characters = string.ascii_letters + string.digits name = ''.join(secrets.choice(characters) for _ in range(10)) upload_dir = './admin/static/upload/' file_name = name+'.png' upload_dir = upload_dir+file_name

    image.save(upload_dir)

    image.show() return "success", {"Content-Type": "text/json"}

image

Your operating system

Windows

Your Python version (python --version)

3.9

Your Robyn version

latest

Additional Info

No response

cbc123 avatar Oct 02 '23 03:10 cbc123

@cbc123 can I work on this??

Oluwaseun241 avatar Oct 05 '23 14:10 Oluwaseun241

I used python-multipart solved.

from multipart import parse_form

...
body = BytesIO(bytearray(request.body))

    def _on_filed(_field):
        pass

    def _on_file(_file):
        with open(_file.file_name, "wb") as f:
            f.write(_file.file_object.getbuffer())

    headers = {
        'Content-Type': request.headers.get("content-type"),
        'Content-Length': request.headers.get("content-length"),
    }
    parse_form(headers, body, on_field=_on_filed, on_file=_on_file)

    return {
        "status_code": 200,
        "type": "text",
    }

goSeeFuture avatar Oct 13 '23 03:10 goSeeFuture

This has been implemented now and should be available in the latest releases

@goSeeFuture @cbc123

sansyrox avatar Apr 22 '24 22:04 sansyrox