Voice Recorder, Saving Blob file to server - C# , Mvc

廉价感情. 提交于 2019-12-01 05:26:39

I went with recorder.js because I wanted the customization — I only needed callbacks I can use with my own UI.

To start with the post, here is the relevant JavaScript code:

Recorder.js upload function

doUpload: function(title, filename) {
    Recorder.upload({
        method: "POST",
        url: "@Url.Action("Upload", "Recordings")",
        audioParam: "Recording", // Name for the audio data parameter
        params: {
            // Additional parameters need to be an object
            "Title": title,
            "FileName": filename
        },
        success: function(response) {
            console.log(response);
        }
    });
}

On the server side, it’s pretty simple. You take a normal controller action with an HttpPostedFileBase parameter to go with the file input. Another way is to use Request.Files. However, in my case, I used a data model to receive the input.

VoicePassage class

public class VoicePassage
{
    public string Title { get; set; }
    public string FileName { get; set; }
    public HttpPostedFileBase Recording { get; set; }
}

The dumbed-down version of how to save the file. This one is really dumbed down. You should be validating input using standard or custom ValidateAttribute/s on your data models. There should be a custom [MimeType("audio/wav")] attribute in the data model somewhere, too.

Dumbed-down version of how to save the file

public JsonResult Upload(VoicePassage passage)
{
    // Validate the input
    // ...
    // ...

    // Save the file
    string path = Server.MapPath(string.Format("~/Recordings/{0}.wav", passage.FileName));
    passage.Recording.SaveAs(path);

    return Json(new { Success: true });
}

The Recorder.upload() function issues an AJAX request to the server, so it makes sense to return a JsonResult rather than an ActionResult. Back on the client-side, you can simply process the result and take action, like append it to a list or display an error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!