Can the image be saved in the folder using javascript? or should that be done on the server side with java?
With Javascript
you can only send the image to the server. With Java
you will have to receive the file and process it.
// Update
but how do I receive the image in the Servlet? Because I put request.getParaeter ("logo"); but he tells me it has to be String.
It is important that you keep the following in mind:
HTML form enctype
When sending files with <form> HTML
, it is necessary to set the enctype
to multipart/form-data
. Example:
<form action="Parametros" methos="POST" enctype="multipart/form-data">
Logo:
<input type="file" id="logo" name="logo" accept="image/*">
<br><br>
Dirección:
<input type="text" id="txtDir" name="txtDir">
<br><br>
<button type="submit" id="btnGuardar">Guardar</button>
</form>
Servlet 3.0 or later:
Set the servlet
with @MultipartConfig
to allow you to recognize and support requests multipart/form-data
and you can use getPart()
. Example:
@WebServlet("/Parametros")
@MultipartConfig
public class ParametrosServlet extends HttpServlet {
// ...
}
The implementation of POST
, you could do it like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Obtiene <input type="text" name="txtDir">
String txtDir = request.getParameter("txtDir");
// ...
// Obtiene <input type="file" name="logo">
Part filePart = request.getPart("logo");
// MSIE fix.
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
// ... código
}
In case you use input file multiple
:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
// Obtiene <input type="file" name="file" multiple="true">
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
for (Part filePart : fileParts) {
// MSIE fix.
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
// ... código
}
}
-
Source: How to upload files to server using JSP / Servlet?