user3398439
user3398439

Reputation: 21

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

We are trying to send our Audio file from the UI side using following code

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"
  });

But we are unable to process that in servlet. Can anybody help me with Javascript code to send audio file to servet and servlet code to save that audio fie in the servlet. Thanks in advance.

Upvotes: 0

Views: 1824

Answers (2)

Harisudan Kuppusami
Harisudan Kuppusami

Reputation: 321

If you want to process the uploaded files in Servlet, files should be sent as request attribute of "multipart/form-data" and it should be POST method

Please refer the example provided by Oracle.

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

Upvotes: 0

Dmitry Nazarenko
Dmitry Nazarenko

Reputation: 346

Good day

You can use a plugin fileupload

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

There is quite full instruction how to use it with spring and ajax:

http://krams915.blogspot.ru/2012/06/file-upload-with-spring-and-jquery-part_2793.html (from wiki of this plugin)

Quick tutorial (don't forget to include the plugin)
Html code:

<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 code:

$(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 spring code:

  @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
}

I hope it'll help you

Upvotes: 1

Related Questions