Ali Zaid wrote:
I'm kinda lost here, and SourceForge search is not working, so I have to
ask, and I'm sorry if this is a repeated question.
The thing is simple, I need a code snippet of how to use ResourceLink to
inatiate a file download.
There are probably simpler ways to do this, but what I did was to
Resource resource = new DownloadableFileResource(filename);
add(ResourceLink("fileLink", resource));
with my own class DownloadableFileResource (attached). I'd love to
hear better solutions, too.
-- Scott
import java.util.Arrays;
import java.util.List;
import wicket.Response;
import wicket.Resource;
import wicket.protocol.http.WebResponse;
import wicket.util.resource.IResourceStream;
import wicket.util.resource.FileResourceStream;
import wicket.util.file.File;
import wicket.util.time.Time;
public class DownloadableFileResource extends Resource {
private String filename;
private static List dontAttach = Arrays.asList(new String[] {
"gif", "jpg", "png", "txt", "html", "pdf"});
public DownloadableFileResource(String filename) {
this.filename = filename;
}
public IResourceStream getResourceStream() {
return new FileResourceStream(new wicket.util.file.File(filename)) {
public String getContentType() {
if (filename.toLowerCase().endsWith(".doc")) {
return "application/msword";
}
return super.getContentType();
}
};
}
public void configureResponse(Response response) {
response.setLastModifiedTime(Time.valueOf(new java.util.Date()));
String extension = filename.substring(filename.lastIndexOf(".") + 1);
if (!dontAttach.contains(extension)) {
((WebResponse) response).setHeader("Content-Disposition",
"attachment; filename=" + (new File(filename).getName()));
}
}
}