我按照这个例子让用户下载 pdf :
/** Copied from example */
@Override
protected void init(VaadinRequest request) {
Button downloadButton = new Button("Download image");
StreamResource myResource = createResource();
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(downloadButton);
setContent(downloadButton);
}
/** modified from example */
private StreamResource createResource() throws IOException {
return new StreamResource(new StreamSource() {
byte[] bytes =loadFile("/home/amira/Desktop/repTest.pdf"); //Get the file bytes here
InputStream is = new ByteArrayInputStream(bytes);
@Override
public InputStream getStream() {
return is ;
}
}, "report.pdf");
}
public static byte[] readFully(InputStream stream) throws IOException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
public static byte[] loadFile(String sourcePath) throws IOException {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
当我尝试打开文件时,它说文件损坏