I’d like to limit the size of the files that users upload on BlackBeltFactory. Currently there are 6GB of pictures, just for the user’s tiny pictures (we keep the originals).
This is my current file upload code:
public abstract class UploadComponent extends Upload
implements Upload.SucceededListener,
Upload.FailedListener,
Upload.Receiver {
protected String directory;
protected File file;
public UploadComponent(String fieldCaption, String buttonCaption, String directoryParam) {
super(fieldCaption, null);
setReceiver( this);
this.directory = directoryParam;
this.setButtonCaption(buttonCaption);
this.addListener((Upload.SucceededListener) this);
this.addListener((Upload.FailedListener) this);
}
@Override
public OutputStream receiveUpload(String filename, String MIMEType) {
FileOutputStream fos = null;
FileUtils.ensureFolderExists(directory);
file = new File(directory, filename);
try {
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
throw new RuntimeException(e);
}
return fos; // Return the output stream to write to
}
public String getDirectory() {
return directory;
}
public File getFile() {
return file;
}
}
My receiveUpload method sends an OuputStream back to Vaadin.
I’d like to limit files to 100Kb max.
I have the same question for the use of “easyuploads” add-on. Is there a possibility to stop or not even start the upload when the file size is too large?
Your code there would probably bug if the browser doesn’t report the content length properly, in which case it will be -1. It can also create a security problem if a user agent fabricates the content length. You should be able to prevent these issues by doing it like this:
@Override
public void updateProgress(long readBytes, long contentLength) {
if (maxSize < readBytes || (contentLength != -1 && maxSize < contentLength)) {
upload.interruptUpload();
Not sure what your change (checking that the contentLength is not -1) is doing…
If contentLength is -1 in the code above, under what circumstance would “maxSize < -1” be true? Presumably the maxSize is not also negative as it would surely trigger the “maxSize < readBytes” anyway. I don’t want any security issues, but not sure I understand the change.
:blink: I was probably writing while sleeping again. I guess this is what I meant what happens easily when you use reverse comparison order…
Thanks! To put it real-ly simple:
@Override
public void updateProgress(long readBytes, long contentLength) {
if (readBytes > maxSize || contentLength > maxSize) {
upload.interruptUpload();
The possible value -1 for the contentLength would cause also other problems in the code.
Also, there’s nowadays a Upload.StartListener, where you can do the contentLength check, and there’s probably no point in doing it again in the ProgressListener.