3

我想实现这一点:上传文件时检查文件扩展名,如果它不是.zip,上传将被中断并向用户显示一条消息,所以我写了这个:

// Implement both receiver that saves upload in a file and
// listener for successful upload
class ReportUploader implements Receiver, SucceededListener {
    public File file;

    public OutputStream receiveUpload(String filename, String mimeType) {
        // Create upload stream
        FileOutputStream fos = null; // Stream to write to
        String userHome = System.getProperty("user.home");

        String ext = filename.substring(filename.lastIndexOf('.'));
        System.out.println("+++++++++++>" + ext);  
        if (!ext.equals(".zip")) {
            Notification.show("Could not upload file", Notification.TYPE_ERROR_MESSAGE);
            return null;
        }
        try {
            file = new File(userHome + "/uploads/report/" + filename);
            fos = new FileOutputStream(file);
        } catch (final java.io.FileNotFoundException e) {
            Notification.show("Could not open file", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
            return null;
        }
        return fos; 
    }

    public void uploadSucceeded(SucceededEvent event) {
        String filename;
        String basepath;
        String folderName;
        String uploadDir;

        filename = event.getFilename();
        basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();
        uploadDir = Utilities.getProperty("uploadDir", basepath + "/WEB-INF/properties/config.properties"); 
        file = new File(uploadDir + filename);
        folderName = filename.substring(0, filename.length() - 5);

        Utilities.unZipFolder(uploadDir + filename, uploadDir + folderName);
        addFilename(folderName);

        try {
            Utilities.deleteCompressedReport(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Notification.show("upload finished", Notification.TYPE_HUMANIZED_MESSAGE); 
    }

    private void addFilename(String sFilename) {
        reportDirList.add(sFilename);
        selectDir.addItem(sFilename);
    }
}  

当扩展名不是 .zip 时,会产生此错误:

com.vaadin.server.UploadException: Upload failed
at com.vaadin.server.communication.FileUploadHandler.streamToReceiver(FileUploadHandler.java:581)
at com.vaadin.server.communication.FileUploadHandler.handleFileUploadValidationAndData(FileUploadHandler.java:419)
at com.vaadin.server.communication.FileUploadHandler.doHandleSimpleMultipartFileUpload(FileUploadHandler.java:382)
at com.vaadin.server.communication.FileUploadHandler.handleRequest(FileUploadHandler.java:267)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1329)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:236)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: com.vaadin.server.NoOutputStreamException
at com.vaadin.server.communication.FileUploadHandler.streamToReceiver(FileUploadHandler.java:518)
... 22 more

那么如何中断上传并显示消息呢?

4

2 回答 2

4

如您所见,您需要调用 Upload 的 interruptUpload 方法。其他几点:

  • 您的 Receiver 在显示错误后返回 null。我发现这会导致日志中出现堆栈跟踪,如果用户将鼠标悬停在 Upload 组件上,部分堆栈跟踪甚至对用户可见。我避免这种情况的方法是返回 NullOutputStream 而不是 null。

  • 如果用户在未先选择文件的情况下尝试上传,您可能还希望防止在 receiveUpload 中出现异常(再次生成堆栈跟踪)。检查空文件名,显示错误,然后返回 NullOutputStream。

    这是一个receiveUpload的例子,它具有上述两种保护。(注意:Utilities.showError只是创建了通常的 Vaadin 通知对话框,没有什么神奇之处。)

        public OutputStream receiveUpload(String filename, String mimeType) {
        if (filename != null && !filename.isEmpty()) {
            // Create upload stream
            FileOutputStream fos = null; // Stream to write to
            try {
                // Open the file for writing.
                file = new File(FileHandler.DEST_PATH + filename);
                fos = new FileOutputStream(file);
                return fos;
            } catch (final java.io.FileNotFoundException e) {
                Utilities.showError("Could not open file<br>", e.getMessage());
            }
        } else {
            Utilities.showError("You must first select a spreadsheet file to upload.");
        }
        uploadControl.interruptUpload();
        return new NullOutputStream(); // to prevent a stack trace from being thrown by Vaadin
    }
    
  • 此外,您可能还需要一个 StartedListener。这是检查文件是否太大的最简单的地方——你可能不想让别人用千兆字节的文件猛烈抨击你。该 uploadStarted 方法可能如下所示:

    public void uploadStarted(StartedEvent event) {
        if (event.getFilename().isEmpty()) {
            uploadControl.interruptUpload();
            Utilities.showError("You must first select a file to upload.");
        } else if (event.getContentLength() > FileHandler.MAX_UPLOAD_BYTES) {
            uploadControl.interruptUpload();
            Utilities.showError("File is too big. Please check that you selected the correct file.");
        } else if (!FileHandler.isValidUploadMIMEType(event.getMIMEType())) {
            uploadControl.interruptUpload();
            Utilities.showError("Unexpected file type. Please check that you selected the correct file.");
        } else {
            progressBar.setValue(0.0f);
            progressBar.setVisible(true);
        }
    }
    

这种方法的一个缺点是我通过避免异常来避免堆栈跟踪。这很好,但上传组件会清除有问题的文件名。如果您抛出异常,您会看到堆栈跟踪,但用户可以看到他们选择的文件,并可能找出他们做错了什么。我决定这是次要的。

于 2014-11-06T03:00:58.017 回答
1

解决方案 :

执行 com.vaadin.ui.Upload.StartedListener.并获取具有扩展名的文件名。如果扩展名无效,请调用 Upload 组件上的方法 interruptUpload()。

于 2013-08-22T13:32:24.997 回答