How to upload a file with Struts2?
I’m trying put an image in a MySQL database through tag <s:file>
in jsp page (I’m using Struts 2):
<s:form action="carica" id="carica" style="display:none">
<s:file id="carica" name="caricaimg"></s:file>
<s:submit value="Carica" ></s:submit>
</s:form>
and in my Class I made this:
public String carica() throws SQLException, FileNotFoundException{
Connessione(); // DB connection method
System.out.print(caricaimg);
File file = new File(caricaimg);
InputStream fin = new java.io.FileInputStream(file);
int fileLength = (int)file.length();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO Utenti (NomeImg, Immagine) VALUES (?, ?)");
pstmt.setString(1, file.getName());
pstmt.setBinaryStream (2, fin, fileLength);
pstmt.executeUpdate();
return "success";
}
Everything looks ok, but when I select an image with <s:file>
it returns only the name of the selected file so when I try to put the image in DB it returns this error
HTTP Status 500 – ImgName.jpg (Unable to found selected file)
This is my struts.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Model" extends="struts-default">
<action name="dati" class="Model.Registrazione" method="execute">
<result name="success">/RegistrazioneRiuscita.jsp</result>
</action>
<action name="login">
<result>/Login.jsp</result>
</action>
<action name="acces" class="Model.Registrazione" method="accesso">
<result name="success">/LoginRiuscito.jsp</result>
<result name="fail">/LoginFallito.jsp</result>
</action>
<action name="modifica" class="Model.Registrazione" method="modifica">
<result name="success">/ModificaRiuscita.jsp</result>
<result name="fail">/ModificaFallita.jsp</result>
</action>
<action name="elimina" class="Model.Registrazione" method="elimina">
<result name="success">/EliminatoSuccesso.jsp</result>
</action>
<action name="carica" class="Model.Registrazione" method="carica">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
This is the part that processes the selected file as method=”POST”
<action name="carica" class="Model.Registrazione" method="carica">
<result name="success">/index.jsp</result>
</action>