gpt4 book ai didi

java - 当某些条件不成立时中断文件上传

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:49:13 27 4
gpt4 key购买 nike

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

  • 您的接收器在显示错误后返回 null。我发现这会导致日志中出现堆栈跟踪,如果用户将鼠标悬停在上传组件上,部分堆栈跟踪甚至对用户可见。我避免这种情况的方法是返回 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);
    }
    }

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

关于java - 当某些条件不成立时中断文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18378918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com