I'm working with Tomcat servlets - jsp
Users upload images that I save in a directory under my web package (same directory for all my jsp pages) and then persist only the path.
When the image is uploaded, and I try to show it by a img tag, they don't appear. BUT if I update classes and resources or restart the server, without any code change, the image displays.
Is there any correct place to store images and avoid this problem? Or should I persist the image itself?
Thanks!
The code where I save the image:
@MultipartConfig
public class ChangeBrandImage extends HttpServlet {
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
DatabaseManager databaseManager = (DatabaseManager) httpServletRequest.getSession().getAttribute("databaseManager");
Part filePart = httpServletRequest.getPart("image");
InputStream fileContent = filePart.getInputStream();
OutputStream outputStream = null;
Admin admin = databaseManager.getAdminDAO().getAdminByEmail(((SimplePrincipal)
httpServletRequest.getSession().getAttribute("org.securityfilter.filter.SecurityRequestWrapper.PRINCIPAL")).getName());
String imageName = Long.toString(System.currentTimeMillis()) + ".jpg";
String path = admin.getBrand().getFolder_path() + "/" + imageName ;
try {
// write the inputStream to a FileOutputStream
outputStream =
new FileOutputStream(new File(path));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileContent != null) {
try {
fileContent.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
// outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Brand brand = admin.getBrand();
BrandDAO brandDAO = databaseManager.getBrandDAO();
brand.setBrand_photo(imageName);
brandDAO.beginTransaction();
brandDAO.update(brand);
try {
brandDAO.commitTransaction();
} catch (DatabaseAccessFailException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
httpServletResponse.sendRedirect("/secured/admins/adminIndex.jsp");
}
}
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
}
@Override
protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
}
}
How I see it: