spark java: how to handle multipart/form-data input?

a 夏天 提交于 2019-12-03 12:08:36
HaiderAgha

The answer provided by Kai Yao is correct except that when using:

request.raw().setAttribute("org.eclipse.multipartConfig", multipartConfigElement);

use this instead:

request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);

I used apache commons-fileupload to handle this.

post("/upload", (req, res) -> {
final File upload = new File("upload");
if (!upload.exists() && !upload.mkdirs()) {
    throw new RuntimeException("Failed to create directory " + upload.getAbsolutePath());
}

// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(upload);
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(req.raw());

// image is the field name that we want to save
FileItem item = items.stream()
                .filter(e -> "image".equals(e.getFieldName()))
                .findFirst().get();
String fileName = item.getName();
item.write(new File(dir, fileName));
halt(200);
return null;
});

See https://github.com/perwendel/spark/issues/26#issuecomment-95077039

By adding a few lines of code to add the multipart config, you can handle multipart/form-data without an external library:

public Object handle(Request request, Response response) {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
    request.raw().setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
    ....
    Part file = request.raw().getPart("file"); //file is name of the upload form
}

Source: http://deniz.dizman.org/file-uploads-using-spark-java-micro-framework/

I found complete example here: https://github.com/tipsy/spark-file-upload/blob/master/src/main/java/UploadExample.java

import spark.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.nio.file.*;
import static spark.Spark.*;
import static spark.debug.DebugScreen.*;

public class UploadExample {

    public static void main(String[] args) {
        enableDebugScreen();

        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'>" // note the enctype
                + "    <input type='file' name='uploaded_file' accept='.png'>" // make sure to call getPart using the same "name" in the post
                + "    <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()) { // getPart needs to use same "name" as input field in form
                Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
            }

            logInfo(req, tempFile);
            return "<h1>You uploaded this image:<h1><img src='" + tempFile.getFileName() + "'>";

        });

    }

    // methods used for logging
    private static void logInfo(Request req, Path tempFile) throws IOException, ServletException {
        System.out.println("Uploaded file '" + getFileName(req.raw().getPart("uploaded_file")) + "' saved as '" + tempFile.toAbsolutePath() + "'");
    }

    private static String getFileName(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

}

Please note that in this example in order to iterate over all files use javax.servlet.http.HttpServletRequest#getParts. Also in this example instead of parsing file name you can simply get it using javax.servlet.http.Part#getSubmittedFileName. And also do not forget to close the stream you get. And also delete the file using javax.servlet.http.Part#delete if needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!