简体   繁体   中英

Upload files to Django Channels through a Websocket connection ( from react native app )

I want to allow users to upload files from the app, it must be through the WebSocket connection and I struggle to find a solution for this, all the solutions I found so far requires setting Content-Type header and for WS connections I can't find anyway to do this

The JavaScript code to upload the files:

const fd = new FormData();
fd.append('uri', uri)

// I get the URI from user gallery expo-image-picker
// The URI looks like this:  file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540zeyadshaban%252Forgachat/ImagePicker/394f4262-184d-4adc-9a51-db32afcb86a2.png

JSON.stringify({
        fd,
        type: 'image',
    })

In the backend (consumers.py) I tried to save the file directly but it keeps throwing an error

elif json_data.get('type') == 'image':
     my_model_instance.image = json_data.get('fd')

await sync_to_async(my_model_instance.save)()

When I insped the json_data.get('fd') in terminal I get this

>> json_data.get('fd')
{'_parts': [[...]]}

I would strongly suggest you do not upload large amounts of data through a websocket connection, it would be better to create another auxiliary http endpoint and have that be used for file upload. The URL encoding of the data used so that it can be inlined in the JSON will multiply the amount of data being transferred by a massive amount.

If you do insist on using WS to upload data then you should be using a binary frame not a JS frame. To include the content type i suggest you do this by creating a dedicated WS endpoint just for upload of data and when you escabilty the connection to it you first send s JSON frame with information (like content type) then after that send lots of Binary frame with the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM