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

限于喜欢 提交于 2019-12-08 06:24:25

问题


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.


回答1:


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?.



来源:https://stackoverflow.com/questions/28123421/how-to-send-an-audio-blobdata-file-from-javascript-to-java-serveraction

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