0

I'm trying to record an audio-file using MediaRecorder and upload the recorded audio to the server's disk afterwards. Recording is no problem so far and I have the BLOB available. All I want to do, is to attach the file to a form, so I can access it in my controller, when the submit button gets clicked.

My JavaScript-Function looks like this:

function sendData(data) {
var fd = new FormData(document.forms["form1"]);
fd.append("AudioFile", data, URL.createObjectURL(data));

Unfortunately it's not available in my controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> NewTerm(NewTermViewModel model)
    {
        var files = HttpContext.Request.Form.Files;

What do I have to do to access the file in my controller?

Thomas
  • 53
  • 5

2 Answers2

0

Here is a link about passing Blob file.And here is a demo about passing xxx.wav file with formdata(You need to use processData: false,contentType: false in ajax):

NewTermViewModel:

public class NewTermViewModel
    {
        public string Name { get; set; }
        public IList<IFormFile> AudioFile { get; set; }
    }

NewTerm.cshtml:

<h1>NewTerm</h1>
<form id="myform">
    @Html.AntiForgeryToken()
    Name:<input asp-for="Name" />
</form>

<input type="file" id="soundFile">
<button onclick="sendData()">sendData</button>
@section scripts{ 
<script type="text/javascript">
    function sendData() {
        var files = $("#soundFile").get(0).files;
        var form = document.forms["myform"];
        var fd = new FormData(form);
        fd.append('AudioFile', files[0]);
        $.ajax({
            type: 'POST',
            url: 'GetAudio',
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            data: fd,
            processData: false,
            contentType: false
        }).done(function (data) {
            console.log(data);
        });
    }
</script>
}

Controller:

[HttpGet]
        public ActionResult NewTerm() {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetAudio(NewTermViewModel model)
        {
            //var files = HttpContext.Request.Form.Files;
            return Json("OK");
        }

result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
0

Use formdata event on your form to get FormData instance related to the form. then append your blob to this instance. do not forget to set enctype of the form to "multipart/form-data" here is an example:

const formElem = document.querySelector('form');
formElem.addEventListener('formdata', (e) => {
    e.formData.append("recordedSound", recordedSoundBlob, "sound.wav");
});
Moseyza
  • 72
  • 12