Home > OS >  Vaadin Upload UnsupportedOperationException issue while creating a File
Vaadin Upload UnsupportedOperationException issue while creating a File

Time:05-23

I'm trying to get a midi file through a form in Vaadin, but when I try to get this File into a File class and getting a UnsupportedOperationException. This is happening in the File midiFile = fileData.getFile();

java.lang.UnsupportedOperationException: class java.io.ByteArrayOutputStream not supported. Use a UploadOutputStream

In the form it seems that the file has been loaded, but there was an error as trying to generate the File. I don't know why is this happening as I follow the methods in Vaadin documentation to get the file from the Upload. And I don't understand why it says in this exception "Happens if outputBuffer is not an UploadOutputStream". https://vaadin.com/api/platform/23.0.9/com/vaadin/flow/component/upload/receivers/FileData.html

And if I run getFileName() from FileData after getting it from the MemoryBuffer I see that the recently uploaded file is there. https://vaadin.com/api/platform/23.0.9/com/vaadin/flow/component/upload/receivers/MemoryBuffer.html

This is the full code.

import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.FileData;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer;

public MainView() {

    MemoryBuffer memoryBuffer = new MemoryBuffer();
    Upload midiFileUpload = new Upload(memoryBuffer);
    midiFileUpload.setDropLabel(new Label("Upload a file in .mid format"));

    midiFileUpload.addSucceededListener(event -> {

        InputStream inputFileData = memoryBuffer.getInputStream();
        String fileName = event.getFileName();
        long contentLength = event.getContentLength();
        String mimeType = event.getMIMEType();
        FileData fileData = memoryBuffer.getFileData();
        
        try {
            File midiFile = fileData.getFile();
        } catch (UnsupportedOperationException uoe) {
            System.out.println("OutputBuffer is not an UploadOutputStream.");
            uoe.printStackTrace();
        } catch (NullPointerException npe) {
            System.out.println("Empty buffer.");
            npe.printStackTrace();
        }
    });
}

CodePudding user response:

I don't know why this issue is happening but I solved it just changing from MemoryBuffer to FileBuffer class. Now it works.

CodePudding user response:

As the name implies, MemoryBuffer stores the uploaded file in memory, so it can't provide a java.io.File, only an InputStream to read the data from. If you want Upload to use a (temporary!) file, use a FileBuffer instead.

  • Related