perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.65k stars 1.56k forks source link

Support file upload #530

Closed andrea-bologna closed 8 years ago

andrea-bologna commented 8 years ago

Hello, is there a simple way to implement a file uplaod?

eyan commented 8 years ago

This might work: http://deniz.dizman.org/file-uploads-using-spark-java-micro-framework/

tipsy commented 8 years ago
File uploadDir = new File("upload");
uploadDir.mkdir(); // create the upload directory if it doesn't exist

staticFiles.externalLocation("upload");

get("/", (req, res) ->
          "<form method='post' enctype='multipart/form-data'>"
        + "    <input type='file' name='uploaded_file' accept='.png'>"
        + "    <button>Upload picture</button>"
        + "</form>"
);

post("/", (req, res) -> {
    Path tempFile = Files.createTempFile(uploadDir.toPath(), "", "");
    req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
    try (InputStream input = req.raw().getPart("uploaded_file").getInputStream()) { 
        Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return "<h1>You uploaded this image:<h1><img src='" + tempFile.getFileName() + "'>";
});
tipsy commented 8 years ago

Added to docs: http://sparkjava.com/documentation.html#examples