Java 当某些条件不正确时中断文件上载
我想实现这一点:在上载文件时,如果文件扩展名不是.zip,则检查文件扩展名,上载将被中断,并向用户显示一条消息,因此我写了以下内容:Java 当某些条件不正确时中断文件上载,java,vaadin,Java,Vaadin,我想实现这一点:在上载文件时,如果文件扩展名不是.zip,则检查文件扩展名,上载将被中断,并向用户显示一条消息,因此我写了以下内容: // Implement both receiver that saves upload in a file and // listener for successful upload class ReportUploader implements Receiver, SucceededListener { public File file; p
// 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
那么如何中断上传并显示消息呢?解决方案:
实现com.vaadin.ui.Upload.StartedListener.and获取具有扩展名的文件名。如果扩展名无效,请调用上载组件上的interruptUpload()方法。正如您所发现的,您需要调用Upload的interruptUpload方法。其他几点:
- 您的接收器在显示错误后返回null。我发现这会导致日志中出现堆栈跟踪,如果用户将鼠标悬停在上载组件上,部分堆栈跟踪甚至对用户可见。我避免这种情况的方法是返回NullOutputStream而不是null
- 如果用户在未选择文件的情况下尝试上载,您可能还希望防止receiveUpload中出现异常(同样,生成堆栈跟踪)。检查空文件名,显示错误,然后返回NullOutputStream 下面是一个示例receiveUpload,它具有上述两种保护。(注意:Utilities.batherRor只创建了通常的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
}
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);
}
}