I have a Rails form with a file field pointing to ActiveStorage. Using the MediaRecorder API (and a polyfill for Safari), I have also built an audio recorder.
So far so good: the recorded audio can be attached to a <audio> element and played, before the form is submitted. As you see below, the code is added as a blob to the <audio> tag.
<audio controls="" data-target="audio-player.player" preload="true" src="blob:http://localhost:3000/5bb2e66f-afc0-6a46-b3f5-a95564afca55"</audio>
The form also allows for a regular file upload of an audio file, which works, and is stored using ActiveStorage, as defined by:
has_one_attached :audio_file
Now I want to submit the whole form, including the audio to Rails. The problem is that is is not possible to directly set the file_field due to browser security constraints.
So I'm trying a workaround: capture the form submit, serialize it and POST with fetch. This is also working (the form needed a remote: true), the only thing now missing is again the audio.
The working callback is:
var form = self.fileFieldTarget.form;
form.addEventListener('submit', function(e){
e.preventDefault();
fetch(e.target.action, {
method: 'POST',
body: new URLSearchParams(new FormData(e.target))
}).then((resp) => {
console.log(resp);
});
});
I see two options:
1) Somehow add the encoded audio to the form json, and have it treated as an ActiveStorage object and then it is all submitted together. 2) Do a separate call to load only the audio, after the rest of form has saved
If some of the HTML / JS looks a bit weird, I am wrapping it all in StimulusJS. I'm happy to share all the audio recording code, if wanted.
