将音频文件/blob 从 UI 发送到 Servlet 以保存在服务器上

Sending Audio file/blob from UI to Servlet for saving at server.

本文关键字:Servlet 保存 存在 服务器 文件 音频 blob UI      更新时间:2023-09-26

我们尝试使用以下代码从UI端发送音频文件

var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = document.getElementById("save");
link.href = url;
link.download = filename || 'output.wav';
var fd = new FormData();
  fd.append('fname', 'sample1.wav');
  fd.append('data', blob);
  $.ajax({
      type: 'POST',
      url: 'AudioToText',
      data: fd,
      processData: false,
      contentType: "audio/wav"
  });

但是我们无法在 servlet 中处理它。任何人都可以帮助我使用Javascript代码将音频文件发送到servt和servlet代码以将该音频fie保存在servlet中。提前谢谢。

美好的一天

您可以使用插件文件上传

https://github.com/blueimp/jQuery-File-Upload

有相当完整的说明如何在 spring 和 ajax 中使用它:

http://krams915.blogspot.ru/2012/06/file-upload-with-spring-and-jquery-part_2793.html(来自此插件的维基)

快速教程(不要忘记包含插件)
网页代码:

<label>Name</label>
    <form name="fileupload" method="POST" class="newSongUpload" action="upload.new.song" id="uploadNewFile">
    <!--in action - your url --!>
                    <input type="text" name="songName">
                        <i class="glyphicon glyphicon-plus"></i>
                            <input type="file" name="files" id="upload-new-document" accept="your accept here">

         </form>
</div>   

JS代码:

$(function () {
            $('.newSongUpload').fileupload({
                multipart: true,
                dataType: 'json'//actually this enough to get plugin works
                //You can write what will happen after loading in done:yourcode and what you accept in accept:your types
            })
        });

Java 弹簧代码:

  @RequestMapping(value = {"/upload.new.song"}, method = RequestMethod.POST)
public @ResponseBody HashMap<String, String> uploadNewSong(HttpServletResponse response,
                                 @RequestParam("file") MultipartFile file){
//Your code with file here you can save it to the database or to file system with file.getBytes() function
}

我希望它能帮助你

如果要在 Servlet 中处理上传的文件,文件应作为"多部分/表单数据"的请求属性发送,并且应该是 POST 方法

请参考甲骨文提供的示例。

参考 : http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html