Search code examples
javafreemarkerspark-framework

Upload file using Spark framework and FreeMarker


I'm trying to make a method to upload files using the spark framework and freemarker but I seem to be hitting a brick wall at the .getPart method. My current freemarker code looks as follows:

<form method='post' enctype='multipart/form-data'>  
    <div>
        <input type='file' name='uploadedFile'>
        <button>Upload csv</button>
    </div>
</form>

and my spark java post method code looks as follows:

post(new Route("/pdf", "multipart/form-data") {
        @Override
        public Object handle(Request request, Response response) {
            String name = null;


            File upLoadM = new File("messages/");

            Path tempFile = null;
            Part file = null;

            try {
                tempFile = Files.createTempFile(upLoadM.toPath(), "", "");
                    System.out.println(tempFile);
            } 
            catch (IOException e1) {
                e1.printStackTrace();
            }


            request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));

            try {
                file = request.raw().getPart("uploadedFile");
                System.out.println(file);
            } 
            catch (IOException | ServletException e1) {
                e1.printStackTrace();
            }

            try (InputStream input = file.getInputStream()) {
                Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
            } 
            catch (IOException e) {
                e.printStackTrace();
            }


            response.status(201);
            response.redirect("/pdf");
            return "";
        }
    });

When i hit the upload button I get a 500 Internal Error. Not sure what the reason it's crashing at the .getPart method is. Any help would be appreciated.


Solution

  • Turns out it is working if i tweek the line of code:

    request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp")); 
    

    to

    request.attribute("org.eclipse.multipartConfig", new MultipartConfigElement("/temp"));