Upload in 24.8.3

Hi,

i recently updatet my vaadin version vom 24.7.latest to the current Version 24.8.3 and lots of component are marked for removal. Currently iam stuck converting my uploads to the new implentation. Here are some full grown example i cant convert.

Here some basic Example i often use. Before Upload i check if the path exists and if not i create it.

Upload bildUpload = new Upload((MultiFileReceiver)(dateiname, mimeType)->{
			File fullpath = new File(pathService.getSpamExamplePath());
			File file = new File(fullpath, dateiname);

 if (!fullPath.exists()) {
               fullPath.mkdir();
               
            }
			try {
				return new FileOutputStream(file);
			}catch(FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		});

Here some more advaneced version.

private Upload projektFotos(SecurityService securityService){

        Mitarbeiter logedInMitarbeiter ....;

Upload bildUpload = new Upload((MultiFileReceiver) (filename, mimeType) -> {

            File fullPath = new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId());

            if (!fullPath.exists()) {
                boolean created = fullPath.mkdir();
                if(!created){
                    System.out.println("Path "+fullPath.getPath()+" cloud not be created!");
                }
            }

            File file = new File(fullPath, filename);

            try {
                return new FileOutputStream(file);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
                return null;
            }
        });

        bildUpload.setMaxFiles(0); // To prevent Uploading a file without selected Project
        bildUpload.setMaxFileSize(20971520);
        bildUpload.setAcceptedFileTypes("image/jpeg", "image/jpg");
        bildUpload.setDropLabel(new Span("Fotoupload jpg jpeg"));

        bildUpload.addFileRejectedListener(e -> Notification.show("Es können nur jpg und jpeg als Bild hochgeladen werden, mit max. 20MB.",5000, Notification.Position.MIDDLE));

        bildUpload.addSucceededListener(e -> {
            try {
                String newFilename = e.getFileName();
                File originalFile = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), newFilename);

                Long id = fotoService.einfuegenFotoBasicDetailsVomProjekt(new Foto(newFilename, projektAuswahl.asSingleSelect().getValue().getId(), 0, logedInMitarbeiter.getId(), LocalDate.now()));

                BufferedImage originalImage = ImageIO.read(originalFile);

                if(originalImage != null){

                    fotoService.updateBildAufloesung(id, originalImage.getWidth(), originalImage.getHeight());

                    BufferedImage originalImageWithWatermark = ImageIO.read(originalFile);

                    BufferedImage resizedImage;

                    if(originalImage.getWidth() > 450){
                        resizedImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_HEIGHT, 450);
                    }else {
                        resizedImage = originalImage;
                    }


                    // Wasserzeichen mit Outline
                    //Setup für Qualität des Renderings
                    Graphics2D graphics2D = (Graphics2D)originalImageWithWatermark.getGraphics();
                    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                    graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                    graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                    graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    //Typ und Text
                    Font font = new Font("Arial", Font.BOLD, 30);
                    String watermarkText = "(C) Companyname";
                    //Wasserzeichen
                    graphics2D.setFont(font);
                    graphics2D.drawString(watermarkText, originalImageWithWatermark.getWidth()-570, originalImageWithWatermark.getHeight()-20);
                    //Outline vom Wasserzeichen
                    TextLayout textLayout = new TextLayout(watermarkText, font, graphics2D.getFontRenderContext());
                    graphics2D.setColor(new Color(0, 0, 0,255));
                    graphics2D.translate(originalImageWithWatermark.getWidth()-570, originalImageWithWatermark.getHeight()-20);
                    Shape shape = textLayout.getOutline(null);
                    graphics2D.draw(shape);


                    File previewImage = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), "Vorschau_"+newFilename);
                    File imageMitWasserzeichen = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), "Wasserzeichen_"+newFilename);
                    ImageIO.write(resizedImage, "jpg", previewImage);
                    ImageIO.write(originalImageWithWatermark, "jpg", imageMitWasserzeichen);
                }

                reloadProjektfotos();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });

        return bildUpload;
    }

My try to convert it.

Upload bildUpload = new Upload(uploadEvent -> {

            FileUploadCallback fileUploadCallbackOnSuccess = (metadata, file) -> {

                try {
                    String newFilename = metadata.fileName();
                    File originalFile = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), newFilename);

                    Long id = fotoService.einfuegenFotoBasicDetailsVomProjekt(new Foto(newFilename, projektAuswahl.asSingleSelect().getValue().getId(), 0, logedInMitarbeiter.getId(), LocalDate.now()));

                    BufferedImage originalImage = ImageIO.read(originalFile);

                    if(originalImage != null){

                        fotoService.updateBildAufloesung(id, originalImage.getWidth(), originalImage.getHeight());

                        BufferedImage originalImageWithWatermark = ImageIO.read(originalFile);

                        BufferedImage resizedImage;

                        if(originalImage.getWidth() > 450){
                            resizedImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_HEIGHT, 450);
                        }else {
                            resizedImage = originalImage;
                        }

                        // Wasserzeichen mit Outline
                        //Setup für Qualität des Renderings
                        Graphics2D graphics2D = (Graphics2D)originalImageWithWatermark.getGraphics();
                        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                        graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                        graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                        //Typ und Text
                        Font font = new Font("Arial", Font.BOLD, 30);
                        String watermarkText = "(C)MyCompany";
                        //Wasserzeichen
                        graphics2D.setFont(font);
                        graphics2D.drawString(watermarkText, originalImageWithWatermark.getWidth()-570, originalImageWithWatermark.getHeight()-20);
                        //Outline vom Wasserzeichen
                        TextLayout textLayout = new TextLayout(watermarkText, font, graphics2D.getFontRenderContext());
                        graphics2D.setColor(new Color(0, 0, 0,255));
                        graphics2D.translate(originalImageWithWatermark.getWidth()-570, originalImageWithWatermark.getHeight()-20);
                        Shape shape = textLayout.getOutline(null);
                        graphics2D.draw(shape);


                        File previewImage = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), "Vorschau_"+newFilename);
                        File imageMitWasserzeichen = new File(new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()), "Wasserzeichen_"+newFilename);
                        ImageIO.write(resizedImage, "jpg", previewImage);
                        ImageIO.write(originalImageWithWatermark, "jpg", imageMitWasserzeichen);
                    }
                    reloadProjektfotos();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            };
            FileFactory fileFactory = (metadata) -> new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId(), metadata.fileName());//File that will be created

            File fullPathToFolder = new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()); //Path where the file will be stored

            if (!fullPathToFolder.exists()) {
                boolean created = fullPathToFolder.mkdir();
                if(!created){
                    System.out.println("Path "+fullPathToFolder.getPath()+" cloud not be created!");
                }
            }

            UploadHandler.toFile(fileUploadCallbackOnSuccess, fileFactory);
        });

        bildUpload.setMaxFiles(0);
        bildUpload.setMaxFileSize(20971520);
        bildUpload.setAcceptedFileTypes("image/jpeg", "image/jpg");
        bildUpload.setDropLabel(new Span("Fotoupload jpg jpeg"));
        bildUpload.addFileRejectedListener(e -> Notification.show("Es können nur jpg und jpeg als Bild hochgeladen werden, mit max. 20MB.",5000, Notification.Position.MIDDLE));

Hi Nils,

do you end up in a specific error message or what exactly is not working in your code?

Cheers

No it shows a green hook for upload done but the file ist not there.

So i got it running but one part is still missing.

Missing part. Befor the Upload starts i like to push this to create the folder if not exsits.

File fullPathToFolder = new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId()); //Path where the file will be stored
if (!fullPathToFolder.exists()) {fullPathToFolder.mkdir();}

Current Version

FileUploadCallback fileUploadCallbackOnSuccess2 = (metadata, file) -> {...Lots of code the first post...       };
        FileFactory fileFactory2 = (metadata) -> new File(pathService.getProjektFotos()+"\\"+projektAuswahl.asSingleSelect().getValue().getId(), metadata.fileName());
        FileUploadHandler fileUploadHandler2 = UploadHandler.toFile(fileUploadCallbackOnSuccess2, fileFactory2);
        Upload bildUpload2 = new Upload(fileUploadHandler2);
        bildUpload2.setMaxFiles(0);
        bildUpload2.setMaxFileSize(20971520);
        bildUpload2.setAcceptedFileTypes("image/jpeg", "image/jpg");
        bildUpload2.setDropLabel(new Span("Fotoupload jpg jpeg"));
        bildUpload2.addFileRejectedListener(e -> Notification.show("Es können nur jpg und jpeg als Bild hochgeladen werden, mit max. 20MB.",5000, Notification.Position.MIDDLE));

Thank you for pushing this topic forward. For a better understanding and reproducing options, what is the outcome of the following methods:

  • pathService.getProjektFotos()
  • projektAuswahl.asSingleSelect().getValue().getId()

Could you also try out the following example on your local machine and how the new API handle the upload.

“pathService” ist a class where i store lots of often used path to networkshares.
“projekAuswahl” is a grid

To store the Uploaded pictures i do the check to and create a folder if required

An example what it could look like:

projectService.getProjectFotos() - return : "\\myserver\projectpictures\"

projektAuswahl.asSingleSelect().getValue().getId() - return:  an id for the project : "150001"

File fullPathToFolder = "\\myserver\projectpictures\150001\; //Path where the file will be stored

The last part checks if the folder 15001 already exits if not it creates the folder.
if (!fullPathToFolder.exists()) {fullPathToFolder.mkdir();}

As long as the folder where the file should be stored is existing it works like mine but if it not exists then not.

In the Old Implementation pre 24.8 this here is a good example. Before the Upload in the try - block i check if the folder where the file should be uploaded to exists. If not it will be created. Where would you put this in “you” git implentation?

Upload bildUpload = new Upload((MultiFileReceiver)(dateiname, mimeType)->{
			File fullpath = new File(pathService.getSpamExamplePath());
			File file = new File(fullpath, dateiname);

 if (!fullPath.exists()) {
               fullPath.mkdir();
               
            }
			try {
				return new FileOutputStream(file);
			}catch(FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		});

like this:

File uploadDir = new File("uploads");
if (!uploadDir.exists() && !uploadDir.mkdirs()) {
    throw new RuntimeException("Failed to create upload directory");
}

return new File(uploadDir, metadata.fileName());

After revieweing you git over and over i got it :smiley:

In line 33 you call this::createFile

private File createFile(UploadMetadata metadata) {

      //HERE I put my check if the folder exits or not
        return new File("uploads", metadata.fileName());
    }

very cool and I’m happy to read that.

I guess the final solution was the type of the return value (which is File and not FOS)?