6

I have a form that has a text input and a file input. Anyway to push that over the socket on submit?

If I add it like this

params.image = $("#new_post_image")[0].files[0]

My params look like this in the channel

%{image: %{}, title: "image title"} 
Peter R
  • 3,185
  • 23
  • 43
  • 1
    It looks like Phoenix's Socket uses `JSON.stringify` to encode the data to be sent, and `JSON.stringify` encodes a `File` to `{}`. One way I can think of is to read the file as a `DataURL` using `FileReader.readAsDataURL` and then decode it on the server but that seems like a hack. `readAsText` will not work as it will mess up binary files and `readAsArrayBuffer` reads into an `ArrayBuffer` which also cannot be directly sent to `JSON.stringify` although you can use http://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string but that again looks like a hack to me. – Dogbert Oct 01 '16 at 08:13
  • 2
    This is very important question. I'm struggling with basically same thing - upload file via channel and JS restrictrions are that it doesn't know about the path of the file, which is crucial for `arc`. I'll check @Dogbert advice. – PatNowak Jan 26 '17 at 20:30
  • @Dogbert have you run into this since -- any updates? – quantumpotato Dec 23 '18 at 23:01
  • I already done a file system with phoenix, and the best solution was uploading the file with a put method (REST) and then process the file with a push on the channel – shop350 Feb 22 '19 at 21:55
  • Am wondering the use case for pushing files through sockets. You could upload the file to s3 and push the pointer through sockets. If you insist on sending through sockets, convert the file to binary and push it down the line. I recommend the former. – osazemeu Apr 02 '19 at 22:20

1 Answers1

0

I would reason that this approach is basically wrong. Instead, the file upload should be handled by a multipart form upload, which should then return a file ID and then you can attach that ID to the form so it keeps the reference.

Alberto
  • 880
  • 5
  • 15