Upload file inside the webapp folder

3

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

I'm currently doing this:

    @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:

How can I set the correct path to this directory?

    
asked by anonymous 22.12.2016 / 19:09

1 answer

1

You need to get the ServletContext to call the getRealPath method:

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

Since you are using a Rest and Jersey API, you will probably be able to get the ServletContext in the service:

@Context
ServletContext context;

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

    
10.03.2017 / 05:36