In order to get a file from HTML and copy it into a specific folder using Java and Glassfish 4.
This is my jsp :
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register</title>
</head>
<body>
<h1>Register !</h1>
<form method="post" enctype="multipart/form-data">
<div>
<label for="username">Username:</label>
<input type="text" name="username" />
</div>
<div>
<label for="username">E-mail:</label>
<input type="text" name="mail" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" />
</div>
<div>
Select File to Upload: <input type="file" name="avatar"/>
</div>
<div>
<input type="submit" value="Submit" />
</div>
<div>
<%
String message = (String) request.getAttribute("erreur");
if(message != null)
out.println( message );
%>
</form>
</body>
</html>
This is my Servlet :
@WebServlet(name = "RegisterServlet", urlPatterns = {"/Register"})
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100 // 100 MB
)
public class RegisterServlet extends HttpServlet {
@EJB
MyuserService MyuserService;
private static final String SAVE_DIR = "uploads";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/register.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String email = req.getParameter("mail");
String password = req.getParameter("password");
// Test des champs
if(username == null || email == null || password == null){
String erreur = "Merci de remplir les champs pour charger le formulaire!";
req.setAttribute("erreur", erreur);
doGet(req, resp);
}
else{
Myuser user = new Myuser();
user.setEmail(email);
user.setPassword(password);
user.setUserName(username);
user.setCreationDate(new Timestamp(new java.util.Date().getTime()));
user.setUserRole(Utils.__USERROLE_UTILISATEUR__);
// gets absolute path of the web application
String appPath = System.getProperty("user.dir");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + SAVE_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : req.getParts()) {
if (part.getName().equalsIgnoreCase("avatar")){
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
}
// Ajout de l'utilisateur en BDD
MyuserService.addMyuser(user);
req.getSession().setAttribute("user", user.getUserName());
resp.sendRedirect(getServletContext().getContextPath());
}
}
/**
* Extracts file name from HTTP header content-disposition
*/
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 "";
}
}
This is my savePath variable return :
/Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/config/uploads
The error :
java.io.FileNotFoundException: /Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/generated/jsp/Myapp/Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/config/uploads/Secu.txt (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at org.apache.catalina.fileupload.PartItem.write(PartItem.java:450)
at org.apache.catalina.fileupload.PartItem.write(PartItem.java:505)
at com.myapp.Servlet.RegisterServlet.doPost(RegisterServlet.java:77)
So the user.dir path is interpreted twiced..