0

I created a image upload using submitUpload() does work when I click in my Button but when I add the submitUpload() in a method doesn't.

This is the class I am using:

// save image
public class ImageUpload implements Receiver{
private File file;
private String foto;
private final String path = "/home/fernando/curriculum/";
private String cpf;

/** add cpf document */
public void setCpf(String cpf){
    this.cpf = cpf;
}

/** save image */
@Override
public OutputStream receiveUpload(String filename, String mimeType) {       
    FileOutputStream fos = null;                
    try{
        file = new File(filename);          
        if(file.getName().endsWith("jpg")){             
            String cpfNumeros = this.cpf.replaceAll("\\.", "").replace("-", ""); //remove mask cpf
            String[] imagem = filename.split("\\."); //get jpg
            String novaImagem = cpfNumeros + "." + imagem[1]; // define name new image

            // new image                
            File newFile = new File(path + novaImagem);
            if(newFile.exists()){
                newFile.delete();                   
            }
            fos = new FileOutputStream(newFile); //salva imagem             
        }else{
            new Notification("Erro de arquivo<br/>", 
                            "Somente arquivos jpg são permitidos", 
                            Notification.Type.ERROR_MESSAGE)
                            .show(Page.getCurrent());
        }           
    }catch(FileNotFoundException ex){
        new Notification("File not found<br/>", 
                     ex.getLocalizedMessage(), 
                     Notification.Type.ERROR_MESSAGE)
                     .show(Page.getCurrent());
        return null;
    }
    return fos;
}   
}


public class ImageUploadView extends CustomComponents {      
    //upload image
    ImageUpload imageUpload = new ImageUpload();
    final Upload upload = new Upload("", imageUpload);
    upload.setCaption("Image");     
    upload.setButtonCaption(null);  
    mainLayout.addComponent(upload);

    Button btnSave = new Button("Save");
    btnSave.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            save(); //call save method          
        }
    });

}

/** save informations on db and save image of user */
private void save(){
     if(!cpf.getValue().trim().isEmpty()){
          imageUpload.setCpf(cpf.getValue());
          upload.submitUpload();     
     }
}

If I call the method save the submitUpload() doesn't work, but when I test submitUpload() directly on Button listener does work.

Any idea ?

Tom
  • 15,798
  • 4
  • 37
  • 48
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118
  • I think the user has to select the file in the webbrowser, I don't think you can use javascript to select a file from the local files system for security reasons. – André Schild Jan 16 '14 at 16:35
  • @AndréSchild the Upload is a component of Vaadin – FernandoPaiva Jan 16 '14 at 16:55
  • Yes, and a vaadin component uses javascript on client side (In the webbrowser) So the same restrictions apply – André Schild Jan 16 '14 at 17:48
  • but the upload works when I use upload.submitUpload() in the button listener. The problem occurs when I call inside some method like save(), can you see ? – FernandoPaiva Jan 16 '14 at 17:59
  • 1) cpf is private variable of ImageUpload class. How save() can access cpf if declared outside the class ? ...am I missing something? 2) ImageUploadView will not compile - could you please check your pasted code? 3) Despite of two above - maybe a silly question: did you set cpf before calling save() ? Is if(!cpf.getValue().trim().isEmpty()) condition met? – wypieprz Jan 16 '14 at 18:15
  • 1) cpf is a private variable but there setCpf(String cpf) method that is public. 2)ImageUpload class compile perfectly and the upload(submitUpload()) works when I click in Button. The problem is when I create method save() and add inside submitUpload(), doesn't work and not returns anything error. – FernandoPaiva Jan 16 '14 at 18:48

1 Answers1

1

Try This One , we are using it:

public class Demographic extends CustomComponent implements Upload.SucceededListener,Upload.FailedListener, Upload.Receiver,Upload.ProgressListener
{
    private Upload uploadPic;
     public Demographic()
     {
        mainLayout = new AbsoluteLayout();
        mainLayout.setImmediate(true);
        mainLayout.setWidth("100%");
        mainLayout.setHeight("100%");
        mainLayout.setMargin(false);

        uploadPic = new Upload("Upload image", this);
        uploadPic.setImmediate(true);
        uploadPic.setWidth("-1px");
        uploadPic.setHeight("-1px");                  
        mainLayout.addComponent(uploadPic, "top:135.0px;left:32.0px;");


        uploadPic.addListener((Upload.SucceededListener) this);
        uploadPic.addListener((Upload.FailedListener) this);          
        uploadPic.addListener((Upload.ProgressListener)this);
      }
      @Override
      public void uploadFailed(FailedEvent event) {
    // TODO Auto-generated method stub

        app.getMainWindow().showNotification("Error! <br />", "Upload Failed due           to: " + event.getReason().getMessage() ,             Window.Notification.TYPE_WARNING_MESSAGE);

      }
    @Override
    public void uploadSucceeded(SucceededEvent event) {
          // all success logic
          if(event.getMIMEType().contains("image")){//mimeType can be made a global variable and can set in Receive upload

        //  System.out.println(event.getFilename());

            savePicture(event.getFilename());// save pic to db from the path provided in receive upload


                app.getMainWindow().showNotification("Success! <br />", "Image upload successful!", Window.Notification.TYPE_TRAY_NOTIFICATION);
            }
        }
    }
    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
         FileOutputStream fos;

        if(mimeType.contains("image")){
          String basePath = getApplication().getContext().getBaseDirectory().getAbsolutePath() + "\\Documents\\"+filename;

          File file= new File(basePath);    
          boolean checkForDir = file.exists();

         if(!checkForDir){
         checkDir.mkdir();
          }
         try {
        // Open the file for writing.
            fos = new FileOutputStream(file);       
           } catch (final java.io.FileNotFoundException e) {

           // Error while opening the file. Not reported here.
                   //e.printStackTrace();

            return null;
         }

        }
        return fos;
    }
}

May be there are syntax errors here but my point is to explain the main logic here

Mubasher
  • 943
  • 1
  • 13
  • 36
  • There is some way to test if user choosed a file before upload ? For example an upload.getValue() that returns if has a file or is not empty ? – FernandoPaiva Jan 16 '14 at 21:48
  • sorry for late replyOn uploadPic press a file chooser will open, in this Dialogue box you will browse your image, let say if you don't pick any file then open will not upload any file, and if you give wrong name then file chooser dialogue will prompt you automatically, on cancel press in file chose also will not upload, – Mubasher Jan 17 '14 at 07:52