3

I'm using the upload component of vaadin(7.1.9), now my trouble is that I'm not able to restrict what kind of files that can be sent with the upload component to the server, but I haven't found any API for that purpose. The only way is that of discarding file of wrong types after the upload.

public OutputStream receiveUpload(String filename, String mimeType) {

    if(!checkIfAValidType(filename)){
        upload.interruptUpload();
    }          

    return out;
}

Is this a correct way?

Skizzo
  • 2,975
  • 8
  • 44
  • 89

5 Answers5

7

No, its not the correct way. The fact is, Vaadin does provide many useful interfaces that you can use to monitor when the upload started, interrupted, finished or failed. Here is a list:

com.vaadin.ui.Upload.FailedListener;
com.vaadin.ui.Upload.FinishedListener;
com.vaadin.ui.Upload.ProgressListener;
com.vaadin.ui.Upload.Receiver;
com.vaadin.ui.Upload.StartedListener;

Here is a code snippet to give you an example:

@Override
public void uploadStarted(StartedEvent event) {
    // TODO Auto-generated method stub
    System.out.println("***Upload: uploadStarted()");

    String contentType = event.getMIMEType();
    boolean allowed = false;
    for(int i=0;i<allowedMimeTypes.size();i++){
        if(contentType.equalsIgnoreCase(allowedMimeTypes.get(i))){
            allowed = true;
            break;
        }
    }
    if(allowed){
        fileNameLabel.setValue(event.getFilename());
        progressBar.setValue(0f);
        progressBar.setVisible(true);
        cancelButton.setVisible(true);
        upload.setEnabled(false);
    }else{
        Notification.show("Error", "\nAllowed MIME: "+allowedMimeTypes, Type.ERROR_MESSAGE);
        upload.interruptUpload();
    }

}

Here, allowedMimeTypes is an array of mime-type strings.

ArrayList<String> allowedMimeTypes = new ArrayList<String>();
allowedMimeTypes.add("image/jpeg");
allowedMimeTypes.add("image/png");

I hope it helps you.

Vikrant Thakur
  • 630
  • 5
  • 7
  • Thanks for your answer, but i think that the MimeType could change from browser to browser – Skizzo Feb 24 '14 at 10:42
  • As far as I know, MIMEType's are standards based and browser independent, although Microsoft IE may have issues in how it handles JavaScript (After all Vaadin Client Side Engine is all JavaScript). Please refer to this link: http://en.wikipedia.org/wiki/Internet_media_type – Vikrant Thakur Feb 27 '14 at 04:15
  • My problem is that even if I call upload.interruptUpload() in uploadStarted(...) my upload will first call receiveUpload(...). There it will create a FileOutputStream and will create a file in my tmp folder... – shinchillahh Jan 15 '16 at 14:16
2

Can be done.

You can add this and it will work (all done by HTML 5 and most browsers now support accept attribute) - this is example for .csv files:

upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");
DarioBB
  • 633
  • 2
  • 8
  • 26
0

I think it's better to throw custom exception from Receiver's receiveUpload:

Upload upload = new Upload(null, new Upload.Receiver() {
    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        boolean typeSupported = /* do your check*/;
        if (!typeSupported) {
            throw new UnsupportedImageTypeException();
        }
        // continue returning correct stream
    }
});

The exception is just a simple custom exception:

public class UnsupportedImageTypeException extends RuntimeException {
}

Then you just simply add a listener if the upload fails and check whether the reason is your exception:

upload.addFailedListener(new Upload.FailedListener() {
    @Override
    public void uploadFailed(Upload.FailedEvent event) {
        if (event.getReason() instanceof UnsupportedImageTypeException) {
            // do your stuff but probably don't log it as an error since it's not 'real' error
            // better would be to show sth like a notification to inform your user
        } else {
            LOGGER.error("Upload failed, source={}, component={}", event.getSource(), event.getComponent());
        }
    }
});
Tomask
  • 1,968
  • 1
  • 22
  • 34
0

public static boolean checkFileType(String mimeTypeToCheck) { ArrayList allowedMimeTypes = new ArrayList();

    allowedMimeTypes.add("image/jpeg");
    allowedMimeTypes.add("application/pdf");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    allowedMimeTypes.add("image/png");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.presentationml.presentation");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    for (int i = 0; i < allowedMimeTypes.size(); i++) {
        String temp = allowedMimeTypes.get(i);
        if (temp.equalsIgnoreCase(mimeTypeToCheck)) {
            return true;
        }
    }

    return false;
}
suneelpervaiz
  • 99
  • 1
  • 5
  • The first line of your code block needs indenting to be properly formatted. I cannot edit it myself since the edit requires fewer than 6 characters changed. – Dillon Davis Jul 27 '18 at 08:19
  • You should also consider adding a brief description to your code to explain what it does. – Dillon Davis Jul 27 '18 at 08:19
0

I am working with Vaadin 8 and I there is no change in Upload class.

FileUploader receiver = new FileUploader();
Upload upload = new Upload();
upload.setAcceptMimeTypes("application/json");
upload.setButtonCaption("Open");
upload.setReceiver(receiver);
upload.addSucceededListener(receiver);

FileUploader is the class that I created that handles the upload process. Let me know if you need to see the implementation.