如何从OutputStream获取byte []以检索上传的文件

时间:2013-12-17 15:28:37

标签: java vaadin

收到上传的文件后,我想返回一个代表上传文件的byte [],我覆盖了receiveUpload方法:

/**
     * 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
    }

那么如何获取byte [],我知道我可以使用ByteArrayOutputStream类检索它,但是我被阻止了。

任何想法都将受到赞赏,

谢谢

3 个答案:

答案 0 :(得分:1)

OutputStream包裹ByteArrayOutputStream,然后使用toByteArray()

答案 1 :(得分:1)

正如kostyan所提到的,你需要使用一个InputStream(关于你的方法意图)。在InputStream中,您可以使用以下内容获取字节:http://lasanthals.blogspot.de/2012/09/get-byte-array-from-inputstream.html

请注意,我提供此作为快速回答,快速搜索,我自己没有尝试过这个。

答案 2 :(得分:0)

问题是当数据完全写入返回的流时如何通知。

您可以使用覆盖ByteArrayOutputStream方法返回close()。当流关闭时,您将知道上传已完全写入该流。

public OutputStream receiveUpload(String filename, String mimeType) {
    return new ByteArrayOutputStream() {
        @Override
        public void close() throws IOException {
            byte[] uploadData = toByteArray();
            //....
        }
    };
}