我希望我的应用程序能够将图像上传到目录中。问题是它有时只在几次尝试后才起作用,尽管有时它可以正常工作。这是我的代码:
这是DemoBean.java
文件
private Part file1;
private String imageName;
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public Part getFile1() {
return file1;
}
public void setFile1(Part file1) {
this.file1 = file1;
}
public String upload() throws IOException {
file1.write("" + getFilename(file1));
imageName = getFilename(file1);
String fileName = "";
try {
Part filePart = file1;
fileName = getFilename(filePart);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File("c:\\project-images\\" + fileName);
inputStream = filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (Exception e) {
System.out.println("shit happened" + e.getCause());
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
//reload();
return "";
}
public void reload() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
}
}
这是使用bean的xhtml
文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="/templates/page-template.xhtml">
<ui:param name="pageTitle" value="Books"/>
<ui:define name="panel-main">
<section>
<h:form enctype="multipart/form-data">
<h2>Add a new Book</h2>
<h:panelGrid columns="2" styleClass="form-grid" columnClasses="form-column-label,form-column-input">
<h:inputFile value="#{demoBean.file1}">
<f:ajax event="change" listener="#{demoBean.upload()}" execute="@form" render="@form"/>
</h:inputFile>
<c:set value="#{demoBean.imageName}" target="#{newBooks.book}" property="image"/>
<h:outputLabel for="Price">Price:</h:outputLabel>
<h:inputText id="Price" value="#{newBooks.book.price}" size="20"/>
<h:outputText value=""/>
<h:commandButton value="Submit" action="#{newBooks.submit}">
</h:commandButton>
</h:panelGrid>
</h:form>
</section>
</ui:define>
</ui:composition>
</html>