I’m trying to generate content and download it after a button click, but I get different outcomes depending on the browser.
I’ve got the book example
// Create an instance of our stream source.
StreamResource.StreamSource imagesource = new MyImageReSource();
// Create a resource that uses the stream source and give it a name.
// The constructor will automatically register the resource in
// the application.
StreamResource imageresource = new StreamResource(imagesource, "myimage.pngs", this);
// Create an embedded component that gets its contents
// from the resource.
embedded = new Embedded();
embedded.setSource(imageresource);
embedded.setType(Embedded.TYPE_BROWSER);
getMainWindow() .addComponent(embedded);
I’ve changed the file extension to “pngs” to prevent the browser to handle it. With Firefox a dialog box is opened to save the file, but nothing happens in Safari, IE or the embedded Eclipse browser (all on Win XP). If I change the Type to OBJECT or IMAGE, the image is rendered in some browsers and not in others, but no dialog save box is open.
I’ve seen in the forum a thread about opening a resource from a new Window and I’ve written this
Window w = new Window("Your data");
w.open(imageresource, "_blank");
getMainWindow().addWindow(w);
In this case Firefox shows the dialog box and the rest of browsers show the image.
Which is the right way to do this that work with any browser?
I’m not entirely sure if this works, but try to manually specify a MIME type for your file. Perhaps that will prevent browsers from guessing what kind of file it is from it’s content.
By default streams are served without “Content-Disposition” parameter in http-header.
If it doesn’t exist, it says to browsers “you decide how to show this”.
You can add it yourself with DownloadStream#setParameter.
Example: to force browsers to always open “save-as” dialog use:
downloadStream.setParameter(“Content-Disposition”, “attachment; filename=” + getFilenameForSaveAsDialogDefautSuggestion());
Or to force browser to show them inside browser (example open pdf inside browser or show image directly):
downloadStream.setParameter(“Content-Disposition”, “inline”);
In your example you use Embedded component - this will acts like an insertion of the image to the web page. If you want to download something to the client followed by a button click, try the following code - replace your button component to a Link component:
public class SaveToExcelButton extends Link
{
public SaveToExcelButton ( StreamResource.StreamSource source )
{
super ();
setCaption ( "Download Image" );
setDescription ( "Download image to your local computer" );
setTargetName ( "_new" );
StreamResource resource = new StreamResource ( source, "picture.png", myApplicationInstance );
resource.setMIMEType ( "application/octet-stream" );
resource.setCacheTime ( 0 );
setResource ( resource );
}
}