File upload inside webapp folder

Asked

Viewed 342 times

3

I have a Rest API with Jersey where I upload files. If I set the path to anywhere else, ex: C:\\uploads works, but would like to save these files inside a webapp directory:

Currently I do so:

    @POST
    @Path("/anexoCliente")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException {

        String uploadedFileLocation = "C:/uploads/" + fileDetail.getFileName();
        writeToFile(uploadedInputStream, uploadedFileLocation);
        String output = "File uploaded to : " + uploadedFileLocation;
        return Response.status(200).entity(output).build();

    }

    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
        try {
            OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];
            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

This is the directory where I want to save the files:

inserir a descrição da imagem aqui

How can I set the right path to this directory?

1 answer

1


You need to get Servletcontext to call the method getRealPath:

String caminho = getServletContext().getRealPath("webapp/uploads/");
File file = new File(caminho);
String caminhoCompleto = file.getCanonicalPath();

Since you’re using a Rest and Jersey API, you’ll probably be able to catch Servletcontext in the service:

@Context
ServletContext context;

Then you can call the equivalent, context.getRealPath().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.