Vishnu Vishnu - 4 months ago 30
Java Question

How to send an audio blob(data) file from javascript to java server(action)?

We are using Struts2 Application wherein I want to send the recorded audio blob file which is in JavaScript, to Java Server (Action Class). I am using the following Ajax code to send the blob file.

Javascript:

var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("filename.wav",blob);
xhr.open("POST","getAudio",true);
xhr.send(fd);


My method in action class is
getAudio()
. So, since it is a data file, how can i receive it in my method and suggest the appropriate xml configuration to receive the same. It would be great, if any ideas. Thanks in advance.

Answer

In Struts2 you can create xml configuration for the action that will be invoked when you send a file.

<action name="getAudio" class="com.example.UploadAction" method="upload">
  <result>success.jsp</result>
</action>

The class should include a method mapped to the action and a properties for the file and its name.

public class UploadAction extends ActionSupport {
  private String name;
  private File file;

  //getter and setter

  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String upload() throws Exception{
      Files.move(file.toPath(),Paths.get("C:\\tmp\\"+name), StandardCopyOption.REPLACE_EXISTING);
      return SUCCESS;
  }
}

Now you should put properties in the form data object

var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
   if(this.readyState === 4) {
       console.log("Server returned: ",e.target.responseText);
   }
};
var fd=new FormData();
fd.append("name", "filename.wav");
fd.append("file", blob);
xhr.open("POST","getAudio",true);
xhr.send(fd);

What is important to know, to be able to deal on the server side with a FormData form, is that it is the same as regular form that has been sent with the encoding multipart/form-data.

And this is important for Struts2 fileUpload interceptor to be able to handle it when the action is invoked.

For the further learning I recommend you to read How can I upload files asynchronously?.