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