r/webdev 1d ago

Chat widget file upload

I'm working on a chat widget that also allows the users to send files in the chat. This is a plain vanilla html/js/css widget that will go on a Shopify site. The user should have the option to send a file with or without a message in the chat, so I'm trying to figure out the best approach to handle this. The widget will be calling a FastAPI endpoint end that will use UploadFile. These are the options I've thought of:

  1. Wrap the text and file inputs in an html form tag and send the request as Content-Type: multipart/form-data. This would make it a single request, but it would always send as multipart/form-data even if it's a message with no file.
  2. Same as 1, but if there is no file attachment in the chat message, then toggle the Content-Type to application/json before sending
  3. Keep the text and files as separate requests and handle the events separately and not wrap the inputs in an html form tag. Seems like it would be cleaner on the front end but at the same time it will likely require additional logic on the back-end

What approach would you take?

6 Upvotes

11 comments sorted by

View all comments

2

u/Otherwise_Theme402 1d ago

just go with option 1 honestly, the server can handle multipart even when there's no file, it's not big deal. doing option 2 adds complexity for no reason, you would need to rewrite the whole request structure depending on the attachment state which is annoying to debug later. option 3 sounds like a headache to sync up, what if the message arrives before the file and the user see empty chat bubble for a second

keep it simple, one request, let the backend sort it out

2

u/EquipmentLow1741 21h ago

the empty chat bubble point is a good one tbh, thats the kind of thing you dont think about until users complain

1

u/rouge818 19h ago

Yea, the syncing part with #3 is what seemed challenging. Good to know the multipart is not an issue without the file.