Spark Java file upload example

In this post we will see how to upload a multipart file using Spark Java. We will have a HTML frontend where user will select a file from his/her system. Then pressing the “Upload” button the file will be posted as multipart data to server. In the server side, the multipart file will be fetched and saved to a defined directory.

Using Spark Java, we can achieve this by writing just few lines of code.

We need only these three files:

  1. build.gradle
  2. index.html
  3. SparkJavaFileUploadSample.java
The files are placed as following folder structure:
Root
│───build.gradle
│
└───src
    └───main
        ├───java
        │   └───com
        │        └─firstfewlines
        │            └SparkJavaFileUploadSample.java
        │
        └───resources
            └───public
                └───index.html
                


Now let us see the content of the files:

1. build.gradle
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'idea'

mainClassName = 'com.firstfewlines.SparkJavaFileUploadSample'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.sparkjava:spark-core:2.6.0'
    compile 'org.slf4j:slf4j-simple:1.7.25'
}

We are including slf4j-simple library to enable the logging messages to be displayed to the console.


2. index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FirstFewLines.com - SparkJava file upload example</title>
</head>
<body>
<h2>FirstFewLines.com - SparkJava file upload example</h2>
<hr>
<div style="display:block">
    <form action="/api/upload" method="post" enctype="multipart/form-data">
        <label for="myfile">Select a file</label>
        <input type="file" id="myfile" name="myfile"/>
        <input type="submit" id="buttonUpload" value="Upload"/>
        <br>
        <p>Result:&nbsp;:<span id="result"></span></p>
    </form>
</div>
</body>
</html>

Note that here specifying enctype=“multipart/form-data” is important. Otherwise the form data might be sent in url encoded format.


3. SparkJavaFileUploadSample.java
package com.firstfewlines;
import static spark.Spark.*;

import spark.utils.IOUtils;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class SparkJavaFileUploadSample {

    public static void main(String [] argv){
        staticFiles.location("/public");

        post("/api/upload", (req, res) -> {
            req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("D:/tmp"));
            Part filePart = req.raw().getPart("myfile");

            try (InputStream inputStream = filePart.getInputStream()) {
                OutputStream outputStream = new FileOutputStream("D:/tmp/" + filePart.getSubmittedFileName());
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();
            }

            return "File uploaded and saved.";
        });
    }
}


How to run the Spark Java application?

  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle run command
  • This should run the application with output similar to below
  • Now open your browser and point to http://localhost:4567/

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.


output:
Starting a Gradle Daemon (subsequent builds will be faster)
:compileJava UP-TO-DATE
:processResources
:classes
:run
[main] INFO spark.staticfiles.StaticFilesConfiguration - StaticResourceHandler configured with folder = /public
[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @158ms to org.eclipse.jetty.util.log.Slf4jLog
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.4.4.v20170414
[Thread-0] INFO org.eclipse.jetty.server.session - DefaultSessionIdManager workerName=node0
[Thread-0] INFO org.eclipse.jetty.server.session - No SessionScavenger set, using defaults
[Thread-0] INFO org.eclipse.jetty.server.session - Scavenging every 600000ms
[Thread-0] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@106a178e{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @253ms
> Building 75% > :run


References:


Download the source code:



Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus