-1
我想知道如何从Vaadin上传组件获取文件。以下是Vaadin Website 上的示例,但不包括除OutputStreams外的其他保存方法。 帮助!如何保存上传文件
我想知道如何从Vaadin上传组件获取文件。以下是Vaadin Website 上的示例,但不包括除OutputStreams外的其他保存方法。 帮助!如何保存上传文件
要接收Vaadin中的文件上传,您必须实现Receiver
接口,它提供了一个用于接收信息的方法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
}
}
如文档中所述,您有一个名为'receiveUpload'的方法。在这种方法中,你需要一个文件名和它的MIME类型。然后你必须使用具有该文件名的“File”创建一个'OutputStream' [(java 7 doc)](https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html)并返回它......当然,“文件”必须位于您想要保存上传的位置。 – Shirkam
@Shirkam我可以有一些代码吗?作为位置C:\ –
是啊为什么不,stackoverflow是你的免费程序员社区... –