我想知道如何从 Vaadin 上传组件获取文件。这是 Vaadin Website 上的示例 但除了有关 OutputStreams 的内容之外,它不包括如何保存它。 救命!
最佳答案
要在Vaadin中接收文件上传,您必须实现Receiver
接口(interface),该接口(interface)为您提供一个receiveUpload(filename, mimeType)
方法,用于接收信息。执行此操作的最简单代码是(以 Vaadin 7 docs 为例):
class FileUploader implements Receiver {
private File file;
private String BASE_PATH="C:\\";
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(BASE_PATH + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
};
这样,Uploader
就会在 C:\
中为您写入一个文件。如果您希望在上传成功完成后执行某些操作,或者不执行某些操作,则可以实现 SucceeddedListener
或 FailedListener
。以上面的示例为例,结果(使用 SucceededListener
)可能是:
class FileUploader implements Receiver {
//receiveUpload implementation
public void uploadSucceeded(SucceededEvent event) {
//Do some cool stuff here with the file
}
}
关于java - 如何保存上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215094/