Estou tentando fazer um upload de arquivos usando jsp + servlet, mas não está funcinando. Segui um exemplo que achei na net, ele não da erro nenhum mas tbem não salva a imagem na pasta upload, a mesma existe pois já verifiquei. As informações sobre o nome o tamanho da imagem e outras que mando imprimir funcionam perfeitamente, apenas não está guardando na pasta, então segue meu código.
jsp
<form action="CommonsFileUploadServlet" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
Servlet
public class CommonsFileUploadServlet extends HttpServlet {
private static final String TMP_DIR_PATH = "/temp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/upload";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
out.println();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
/*
*Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
/*
* Set the temporary directory to store the uploaded files of size above threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
//Handle Uploaded files.
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize()/1024 + "KB");
/*
* Write file to the ultimate location.
*/
File file = new File(destinationDir,item.getName());
item.write(file);
}
out.close();
}
//response.sendRedirect("cadEnsaio.jsp");
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}