Java 如何从OutputStream获取字节[]以检索上载的文件
收到上传的文件后,我想返回一个字节[],表示上传的文件,我覆盖了receiveUpload方法:Java 如何从OutputStream获取字节[]以检索上载的文件,java,vaadin,Java,Vaadin,收到上传的文件后,我想返回一个字节[],表示上传的文件,我覆盖了receiveUpload方法: /** * Invoked when a new upload arrives. * * @param filename * the desired filename of the upload, usually as specified * by the client. * @param mi
/**
* Invoked when a new upload arrives.
*
* @param filename
* the desired filename of the upload, usually as specified
* by the client.
* @param mimeType
* the MIME type of the uploaded file.
* @return Stream to which the uploaded file should be written.
*/
public OutputStream receiveUpload(String filename, String mimeType);
但它返回一个OutputStream
以下是完整的实现:
class FileUploaderReceiver implements Receiver{
public File file;
@Override
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
OutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File("/tmp/uploads/" + 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
}
类FileUploaderReceiver实现接收器{
公共文件;
@凌驾
public OutputStream receiveUpload(字符串文件名,
字符串(mimeType){
//创建上传流
OutputStream fos=null;//要写入的流
试一试{
//打开文件进行写入。
file=新文件(“/tmp/uploads/”+文件名);
fos=新文件输出流(文件);
}捕获(最终java.io.filenotfounde异常){
新通知(“无法打开文件
”,
e、 getMessage(),
通知.Type.ERROR(错误消息)
.show(Page.getCurrent());
返回null;
}
return fos;//返回要写入的输出流
}
因此,如何获取字节[],我知道我可以使用ByteArrayOutputStream类检索它,但我被阻塞了
任何想法都将受到欢迎
谢谢您用
ByteArrayOutputStream
将输出流
包装起来,然后使用。正如kostyan提到的,您需要使用一个InputStream(与您的方法意图有关)。从InputStream中,您可以使用如下方式获取字节:
请注意,我提供了一个快速的答案,通过快速搜索,我自己还没有尝试过这个答案。问题是如何在数据完全写入返回流时得到通知 您可以使用重写的
close()
方法返回ByteArrayOutputStream
。当流关闭时,您将知道上载已完全写入该流
public OutputStream receiveUpload(String filename, String mimeType) {
return new ByteArrayOutputStream() {
@Override
public void close() throws IOException {
byte[] uploadData = toByteArray();
//....
}
};
}
我认为您需要的是
InputStream
,而不是输出,您试图读取文件,而不是写入文件。