<h:form>
...
<p:fileUpload id="slike" fileUploadListener="#{oglasBean.handleFileUpload}" cancelLabel="Otkaži" label="Dodaj"
mode="advanced" dragDropSupport="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" update="poruka"/>
<div/>
<br />
<p:commandButton value="Dodaj oglas"
action="#{oglasBean.dodajOglas()}" />
...
</h:form>
备份bean代码:
public void handleFileUpload(FileUploadEvent event) {
System.out.println(event.getFile().getFileName());
oglas.setSlika(event.getFile());
}
public void dodajOglas(){
Date datum = new Date();
oglas.setDatumKreiranja(datum);
if(oglas.getVrsta().equals("besplatan")){
oglas.setTrajanje(1);
oglas.setCijena(0);
}
else{
}
if (OglasDAO.dodajOglas(oglas)) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,"Uspješno ste dodali sliku.", "");
FacesContext.getCurrentInstance().addMessage(null, message);
}
else{
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Dodavanje slike nije uspjelo!", "");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
用于添加到数据库的DAO方法,实际上是问题所在:
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import net.etfbl.traveladvertiser.model.Oglas;
public class OglasDAO {
private static String DODAJ_OGLAS = "insert into oglas values (tekst, slika,
vrsta, trajanje) values (?, ?, ?, ?)";
public static boolean dodajOglas(Oglas oglas){
Connection conn = null;
try{
conn = ConnectionPool.getConnectionPool().checkOut();
PreparedStatement stm = conn.prepareStatement(DODAJ_OGLAS);
InputStream instream = oglas.getSlika().getInputstream();
stm.setString(1, oglas.getTekst());
stm.setBinaryStream(2, instream, oglas.getSlika().getSize());
stm.setString(3, oglas.getVrsta());
stm.setInt(4, oglas.getTrajanje());
stm.executeUpdate();
stm.close();
return true;
}
catch(Exception ex){
ex.printStackTrace();
return false;
}
finally{
ConnectionPool.getConnectionPool().checkIn((com.mysql.jdbc.Connection) conn);
}
}
}
它在刀口断了
InputStream instream = oglas.getSlika().getInputstream();
带着信息:
java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\TravelAdvertiser\upload_fd4813af_24f6_485e_a865_5aa9be1a871d_00000019.tmp (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.getInputStream(DiskFileItem.java:188)
at org.apache.catalina.core.ApplicationPart.getInputStream(ApplicationPart.java:99)
at org.primefaces.model.NativeUploadedFile.getInputstream(NativeUploadedFile.java:45)
at net.etfbl.traveladvertiser.DAO.OglasDAO.dodajOglas(OglasDAO.java:17)
at net.etfbl.traveladvertiser.beans.OglasBean.dodajOglas(OglasBean.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
我的猜测是Tomcat由于某种原因无法写入temp文件夹。奇怪的是,它实际上包含了我昨天用这个应用上传的一些文件,而且它刚刚停止工作。所以,也许问题是我忘记了代码中的一些小东西(做了很多修改和试验)?