Reputation: 557
Can file be downloaded using
AjaxLink<Void> downloadButton = new AjaxLink<Void>("downloadButton") {
@Override
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
}
? Or it can only happen with onSubmit()
action? Because I have a working code of downloading a file with a button click, but that method uses onSubmit
. Now I am trying to do the same action with this kind of button, it prepares the file the same way, it even creates a temporary file in my local files, but when it comes to the popup in browser it just doesn't do anything. What could be the problem?
Edit:
Here is the working code, but if I use the same code in my AjaxLink it doesn't work properly as stated before:
@Override
protected void onSubmit() {
super.onSubmit();
File file = null;
try {
file = File.createTempFile("temp-file-name", ".csv");
String data = getData();
if (data == null) {
FileUtils.writeByteArrayToFile(file, ("").getBytes());
} else {
FileUtils.writeByteArrayToFile(file, data.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
if (file == null) {
throw new IllegalStateException(getClass().getName() +
" failed to retrieve a File object from model");
}
final File preparedFile = file;
IResourceStream resourceStream = new FileResourceStream(
new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(
new ResourceStreamRequestHandler(resourceStream) {
@Override
public void respond(IRequestCycle requestCycle) {
super.respond(requestCycle);
Files.remove(preparedFile);
}
}.setFileName("Report.csv")
.setContentDisposition(ContentDisposition.ATTACHMENT));
}
}
}
Upvotes: 0
Views: 621
Reputation: 17513
You cannot just stream a file in Ajax response.
You need to use Wicket's AjaxDownloadBehavior. It provides logic to overcome this restriction.
Demo code: https://github.com/apache/wicket/blob/0ba3ce015ae9f258246b92ac599a00481a26c37f/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/AjaxDownloadPage.java Demo in action: http://examples8x.wicket.apache.org/ajax/download
Upvotes: 2