I have created a class for Download of Files
public class DownloadLink extends Anchor {
private static final long serialVersionUID = 1L;
public DownloadLink(File file) {
Anchor anchor = new Anchor(getStreamResource(file.getName(), convertFileToString(file)), file.getName());
anchor.getElement().setAttribute("download", true);
anchor.setHref(getStreamResource(file.getName(), convertFileToString(file)));
add(anchor);
}
public StreamResource getStreamResource(String filename, String content) {
return new StreamResource(filename, () -> new ByteArrayInputStream(content.getBytes()));
}
private String convertFileToString(File file) {
StringBuilder fileContents = new StringBuilder((int) file.length());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + System.lineSeparator());
}
return fileContents.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
I can call this class by
File in = new File("C:\\dev\\wcontent\\mail\\attachments\\575\\Demo.txt");
DownloadLink downloadLink = new DownloadLink(in);
add(downloadLink);
This code works well for pure Textfiles.
But it works not for other Files with other Content-Types like pdf, jpg, images, …
Can you help me, that it works also for images, pdf, …