编程语言
首页 > 编程语言> > java – 某些条件不正确时中断文件上载

java – 某些条件不正确时中断文件上载

作者:互联网

我想实现这个:在上传文件检查文件扩展名时,如果它不是.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

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

解决方法:

如您所见,您需要调用Upload的interruptUpload方法.其他一些观点:

>您的Receiver在显示错误后返回null.我发现这会导致日志中的堆栈跟踪,如果用户将鼠标悬停在Upload组件上,则部分堆栈跟踪甚至可供用户看到.我避免这种情况的方法是返回NullOutputStream而不是null.
>如果用户在未先选择文件的情况下尝试上传,您可能还希望在receiveUpload中防止异常(再次生成堆栈跟踪).检查空文件名,显示错误,然后返回NullOutputStream.

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

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

这种方法的一个缺点是我通过避免异常来避免堆栈跟踪.哪个没问题,但上传组件清除了有问题的文件名.如果您抛出异常,您会看到堆栈跟踪,但用户可以看到他们选择的文件,并可能弄清楚他们做错了什么.我觉得这很小.

标签:java,vaadin
来源: https://codeday.me/bug/20190831/1776892.html