java - 如何使用休眠导入图片
问题描述
我正在尝试制作用户个人资料,我需要为每个用户上传一张图片。我想知道如何使用 Hibernate 和 Jsp 导入用户个人资料图片?我找到了这段代码,但在提交表单后出现错误,这是我的 servlet
添加.java:
@WebServlet(name = "add", urlPatterns = {"/add"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
public class add extends HttpServlet {
public static final String UPLOAD_DIR = "resources";
PrintWriter out;
HttpSession session;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
Session sessionh = HibernateUtil.getSessionFactory().openSession();
sessionh.beginTransaction();
try {
out = response.getWriter();
session = request.getSession();
PasswordGen pG=newPasswordGen(8,ThreadLocalRandom.current());
Part part = request.getPart("photo");
String photo = extractFileName(part);
String path = UPLOAD_DIR + "/" + photo;
String applicationPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
System.out.println("applicationPath: " + applicationPath);
File fileUploadDirectory = new File(applicationPath);
if (!fileUploadDirectory.exists()) {
fileUploadDirectory.mkdirs();
}
String savePath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR + File.separator + photo;
File fileSaveDir = new File(savePath);
part.write(savePath + File.separator);
String password = pG.nextString();
Etudiant st = new Etudiant();
st.setPhoto(path);
st.setPasswordEtudiant(password);
sessionh.save(st);
sessionh.getTransaction().commit();
sessionh.close();
if (st != null) {
session.setAttribute("username",st.getNomEtudiant());
session.setAttribute("image", path);
session.setAttribute("email", st.getEmailEtudiant());
request.setAttribute("msg", "Etudiant ajouter");
request.getRequestDispatcher("addStudent.jsp").forward(request, response);
} else {
response.sendRedirect("error.jsp");
}
} catch (ParseException ex) {
Logger.getLogger(addStudent.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
}
解决方案
推荐阅读
- python - 如何使用命令行导入模块?
- python - 如何在 python 中使用 BeautifulSoup 从以下链接返回日期和标题
- r - r中两个数据集的散点图
- python - 打开命令是否(或不)锁定文件?
- apache - 使用 Let's encrypt with Apache 和 Apache Tomcat
- python - 如何确定python中变量的类型?
- android - 将 firestore firebase 放入回收站时为 null
- javascript - API 总是返回 200,响应中没有数据
- azure - 通过 Matillion 从 blob 中解密文件
- postman - 在 Postman 中是否只运行部分请求?