Get name of a file

0

I'm doing a web app with jsp, I try to make a form that includes a photo in this way

<form name="AddCat" action="../Insertar" method="post" enctype="multipart/form-data">

This form is sent to a servlet that supports multipart

@WebServlet(name = "Insertar", urlPatterns = {"/Insertar"})
@MultipartConfig

And in the dopost method I do the following

String nombre=request.getParameter("nombreCat");
Part archivo = request.getPart("archivos"); //para el input que contiene la foto
InputStream streamArchivo = archivo.getInputStream();
   //EL if solo es para checar que haya recibido algo jeje
   if(streamArchivo!=null)
   {                
    System.out.println("recibió");
   }

   else 
    System.out.println("vació");

   System.out.println(nombre);

Since I received that file that apparently if it does, I would like to get the extension of the file and the path where it is to be able to copy it to a special folder within my project, any ideas? Thanks

    
asked by Missael Armenta 10.06.2016 в 17:32
source

1 answer

1

Use Part#getSubmittedFileName .

Keep in mind that the only information that is sent is the name of the file. From the server, you will not know the full path where the file is located on the client side, mainly because it is not relevant information for the server and security issues (you will not reveal such particular information of the client).

If you need to copy it to a route within your project, I recommend that you create a folder on the server and deposit there the content of the file that is in InputStream .

File carpetaDestino = new File("/alguna/ruta/en/el/servidor");
File archivoDestino = new File(carpetaDestino, archivo.getSubmittedFileName());
InputStream streamArchivo = archivo.getInputStream();
Files.copy(streamArchivo, archivoDestino .toPath());

To place the action routes in the forms, it is best to use ${pageContext.request.contextPath} and thus have absolute paths regardless of where the resource is located.

Change this:

<form name="AddCat" action="../Insertar" ...>
                            ^
                            |-- malo!

Because of this:

<form name="AddCat" action="${pageContext.request.contextPath}/Insertar" ...>
    
answered by 10.06.2016 / 17:39
source