I need a validator for an upload file, for the moment I can upload all the files but I need a check that file is less than 10 MB and only text format such as ms word, txt, ppt, excel (not executable, might be harmful). Do I have to use and libraries of java for that, or I don't know what, cause I am a junior. If anyone has any ideas that will be very nice. I have seen some other similar question and i try out but none that can help me. Ps: I am working on java spring.
Here is my code is compiled but not working is possible edit and also to check for the length.
class FileUploader implements Receiver, SucceededListener, FailedListener, ProgressListener {
private static final long serialVersionUID = 1L;
public File file;
public String filename;
@Override
public void updateProgress(long readBytes, long contentLength) {
UI ui = UI.getCurrent();
ui.access(() -> {
progressBar.setCaption("Uploaded: " + (float) readBytes / (float) contentLength * 100 + "%");
progressBar.setValue((float) readBytes / (float) contentLength);
progressBar.setVisible(true);
});
}
@Override
public void uploadFailed(FailedEvent event) {
UIHelper.showErrorNotification("File could not be uploaded");
}
@Override
public void uploadSucceeded(SucceededEvent event) {
try {
String savePath = "/var/ccpt_work_files/";
Path filePath = Paths.get(savePath);
if (Files.exists(filePath)) {
copyFiles("/tmp/" + event.getFilename(), savePath + event.getFilename(), savePath + event.getFilename());
} else {
File targetFile = new File(savePath);
if (!targetFile.mkdirs()) {
UIHelper.showErrorNotification("Couldn't create dir: " + targetFile);
} else {
copyFiles("/tmp/" + event.getFilename(), savePath + event.getFilename(), savePath + event.getFilename());
}
}
} catch (IOException e) {
UIHelper.showErrorNotification("File could not be uploaded");
}
UIHelper.showInformationNotification("File successfully uploaded");
}
private void copyFiles(String from, String to, String finalPath) throws IOException {
com.google.common.io.Files.copy(new File(from), new File(to));
uploadedFilePath = finalPath;
}
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
this.filename = filename;
FileOutputStream fos = null;
try {
file = new File("/tmp/" + filename);
fos = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
} catch (final IOException e) {
UIHelper.showErrorNotification("File could not be stored in server");
return null;
}
return fos;
}
};