我正在使用Tomcat servlet - jsp
用户上传我保存在我的web包下的目录中的图像(我所有jsp页面的相同目录),然后只保留路径。
当图片上传时,我尝试通过img标签显示图片时,它们不会显示。但是,如果我更新类和资源或重新启动服务器,而不进行任何代码更改,则会显示图像。
是否有正确的位置来存储图像并避免此问题?或者我应该坚持图像本身?
谢谢!
我保存图片的代码:
@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 {
}
}
我怎么看: