【问题标题】:Upload image doesn't work?上传图片不起作用?
【发布时间】:2014-01-16 16:09:03
【问题描述】:

我使用submitUpload() 创建的图像上传在我单击按钮时确实有效,但当我在方法中添加submitUpload() 时却无效。

这是我正在使用的课程:

// 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();     
     }
}

如果我调用方法保存 submitUpload() 不起作用,但是当我直接在 Button 侦听器上测试 submitUpload() 时确实有效。

有什么想法吗?

【问题讨论】:

  • 我认为用户必须在网络浏览器中选择文件,出于安全原因,我认为您不能使用 javascript 从本地文件系统中选择文件。
  • @AndréSchild 上传是 Vaadin 的一个组件
  • 是的,vaadin 组件在客户端使用 javascript(在 webbrowser 中)所以同样的限制适用
  • 但是当我在按钮监听器中使用 upload.submitUpload() 时,上传工作。当我在 save() 之类的方法中调用时会出现问题,你能看到吗?
  • 1) cpf 是 ImageUpload 类的私有变量。如果在类外声明 save() 如何访问 cpf ? ......我错过了什么吗? 2) ImageUploadView 将无法编译 - 你能检查你粘贴的代码吗? 3)尽管有上述两个——也许是一个愚蠢的问题:你在调用 save() 之前设置了 cpf 吗?是否满足 if(!cpf.getValue().trim().isEmpty()) 条件?

标签: java vaadin vaadin7


【解决方案1】:

试试这个,我们正在使用它:

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;
    }
}

这里可能有语法错误,但我的意思是解释这里的主要逻辑

【讨论】:

  • 有一些方法可以测试用户是否在上传之前选择了一个文件?例如,如果有文件或不为空,则返回 upload.getValue() ?
  • 抱歉回复晚了On uploadPic 按下文件选择器将打开,在此对话框中您将浏览您的图像,假设您没有选择任何文件然后打开不会上传任何文件,如果您输入错误的名称,然后文件选择器对话框将自动提示您,取消时按选择的文件也不会上传,
猜你喜欢
  • 2013-06-23
  • 2014-06-21
  • 1970-01-01
  • 2016-08-15
  • 2017-05-05
  • 2015-02-21
  • 1970-01-01
相关资源
最近更新 更多