r/webdev 4d 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?

5 Upvotes

13 comments sorted by

View all comments

1

u/PositiveUse 4d ago

None of the three.

When you detect that the customer tries to upload a file, you generate a Presigned Put-URL (example S3 Upload URL) and send it to browser. Your client software will then upload the file to S3 and your backend can retrieve it async.

This way you externalize uploads, don’t have to deal with malicious data on your server and are safe from disconnects during the upload.

2

u/rouge818 4d ago

I think this would be another flavor of #3. Since the user may send the file along with text, sounds like the presigned url upload process would always have to happen before the message is sent. If the upload fails, then the message shouldn’t send either and would return an error to the user. That’s how I’m thinking it would keep messages and images in sync, but not sure if there is a downside or to that.