bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
38.19k stars 1.3k forks source link

htmx.ajax() with multipart/form-data? #416

Open gmzu opened 3 years ago

gmzu commented 3 years ago

Is it possible to use htmx.ajax () to send a content type of type multipart/form-data? I have to send to server a File Object (previously manipulated in memory via js). "values" property of context object seems to accept only json

BoPeng commented 3 years ago

Not quite sure about the context but did you look at hx-encoding="multipart/form-data"?

gmzu commented 3 years ago

@BoPeng thanks for your reply

  1. Using hx-encoding="multipart/form-data" and hx-vars it works without calling htmx.ajax(). I hadn't used 'hx-vars' initially as the documentation reports that hx-vars has been deprecated in favor of hx-vals. "Deprecated" confused me, I figured it was a feature that would be removed from new releases. Will it remain in future versions? Why is it not present in reference section? It is really useful!
  2. Using hx-encoding="multipart/form-data" on the element that triggers the call to htmx.ajax() (using for example hyperscript code_="on click call htmx.ajax('POST','/example',{values:{file:fileObject}})) does not change the type of content type that remains application/x-www-form-urlencoded and I could not check if fileObject is correctly transmitted
1cg commented 3 years ago

Unfortunately right now that won't work because we don't detect the content type. I will try to make this work when I have some time, but it might be a bit. Sorry about that.

Regarding hx-vars being deprecated, you can use hx-vals:javascript: to get the same behavior. I think I'm going to un-deprecate hx-vars though. :)

yaakovLowenstein commented 8 months ago

Is there a workaround for this. This is pretty important to me to be able to do. I'm working on code that already has things in place, therefore I am trying to create a wrapper that uses htmx to submit the form and update the page. However, not being able to submit documents with htmx.ajax is limiting.

I would love to contribute and enable this feature. I looked at the code and did some looking around and it looks like the only way to submit files with a XMLHttpRequest is to use FormData. Is that what you had in mind? (https://stackoverflow.com/questions/9395911/send-a-file-as-multipart-through-xmlhttprequest)