'How to send an audio blob (data) file from JavaScript to Java server action in Struts 2?
We are using Struts2 Application where in 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.
Solution 1:[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
FormDataform, is that it is the same as regular form that has been sent with the encodingmultipart/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?.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
