Solution of my case:
PrintWriter out = response.getWriter();
Map<String, String> fields = new HashMap<>();
Map<String, List<String>> multiValueFields = new HashMap<>();
if (!ServletFileUpload.isMultipartContent(request)) {
out.println("Nothing to upload");
return;
}
FileItemFactory itemfactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(itemfactory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String contentType = item.getContentType();
if (!contentType.equals("image/png")) {
out.println("only png format image files supported");
continue;
}
File uploadDir = new File("C:\\");
File file = File.createTempFile("img", ".png", uploadDir);
item.write(file);
fields.put("imagem", file.getPath());
out.println("File Saved Successfully");
} else {
String name = item.getFieldName();
String value = item.getString();
if (!multiValueFields.containsKey(name)) {
multiValueFields.put(name, new ArrayList<String>());
}
fields.put(name, value);
multiValueFields.get(name).add(value);
}
}
String nome = fields.get("nome");
String descricao = fields.get("descricao");
String tipo = fields.get("tipo");
String nomeImagem = fields.get("imagem");
List<String> opcao = multiValueFields.get("opcao");
Exercicio e = new Exercicio();
e.setNome(nome);
e.setTipo(tipo);
e.setDescricao(descricao);
Instrutor i = new Instrutor(request.getSession().getAttribute("usuario").toString());
e.setInstrutor(i);
e.setImagem(nomeImagem);
ExercicioDAO dao = new ExercicioDAO();
dao.cadastrar(e); //cadastra no db o obj exercicio
} catch (FileUploadException e) {
e.printStackTrace();
out.println("upload fail");
} catch (Exception ex) {
ex.printStackTrace();
out.println("can't save");
}
It does not work, only comes the name of the file in Servlet, in the case.png file
– ayowole agbedejobi
in your question you talk about how to take the html or jsp data and put it in Servlet
– User1999
when you click the button it sends to the specified Rvlet ?
– User1999
I need to handle the file on Servlet
– ayowole agbedejobi
in case I want to know how I take the file to send to db or send to a specific folder
– ayowole agbedejobi
post your Servlet code and the class responsible for persisting the data in the database
– User1999