简体   繁体   中英

Preview image before upload in struts 2.3

I want to upload a file in database using struts2 but the problem is I want to show the photo when I select the photo on the same page.

Image will show the these of the program.

在此输入图像描述

index.jsp

  <s:form action="UploadAction.action" enctype="multipart/form-data">
    <s:textfield name="ename" required="true" label="Emp Name" />
    <s:file name="photo" label="Photo" required="true" />
    <s:submit value="U P L O A D" />

</s:form>

UAction.java

  public class UAction {

String ename, photo, msg;

public String execute() throws Exception {
    msg = com.db.Admin.addemp(ename, photo);
    setEname("");
    return "SUCCESS";
}

Photo.java

  public class Photo extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String empno = request.getParameter("e");
    try {
        ResultSet rs = com.db.Admin.getPhoto(empno);
        if (rs.next()) {
            Blob ph = (Blob) rs.getBlob(1);
            byte data[] = ph.getBytes(1, (int) ph.length());
            ServletOutputStream out = response.getOutputStream();
            out.write(data);
        }
    } catch (Exception e) {
        e.getMessage();
    }
}

}

Admin.java

  public static String addemp(String ename, String photo) {
    try {
        CallableStatement cs = connect().prepareCall("{call addEmp(?,?,?)}");

        cs.setString(1, ename);
        FileInputStream r = new FileInputStream(photo);
        cs.setBinaryStream(2, r);
        cs.registerOutParameter(3, Types.VARCHAR);
        cs.execute();
        return cs.getString(3);
    } catch (Exception e) {
        return e.getMessage();
    }
}

public static ResultSet getData() throws Exception {
    return connect().prepareCall("{call getData()}").executeQuery();
}

public static ResultSet getPhoto(String empno) throws Exception {
    CallableStatement cs = connect().prepareCall("{call getPhoto(?)}");
    cs.setString(1, empno);
    return cs.executeQuery();
}

}

This should be done with some javascript code.

<img id="imagePlaceHolder" alt="your image" width="100" height="100" />
<s:file name="photo" label="Photo" required="true"  
    onchange="document.getElementById('imagePlaceHolder').src = window.URL.createObjectURL(this.files[0])" 
/>

You can find more solutions at Preview an image before it is uploaded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM