简体   繁体   中英

Retrieving binary file from post request

Sending a POST request (Apache httpclient, here Kotlin source code):

val httpPost = HttpPost("http://localhost:8000")
val builder = MultipartEntityBuilder.create()
builder.addBinaryBody("file", File("testFile.zip"),
        ContentType.APPLICATION_OCTET_STREAM, "file.ext")
val multipart = builder.build()
httpPost.entity = multipart
val r = httpClient.execute(httpPost)
r.close()

I receive the request in my post handler as a via spark-java Request-object. How do I retrieve the original file (plus the file name as a bonus) from the post request? The request.bodyAsBytes() method seems to add some bytes because the body is larger than the original file.

Thanks, Jörg

Near the bottom of Spark's Documentation page there is a section "Examples and FAQ" . The first example is "How do I upload something?". From there, it links further to an example on GitHub .

In short:

post("/yourUploadPath", (request, response) -> {
    request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
    try (InputStream is = request.raw().getPart("file").getInputStream()) {
        // Use the input stream to create a file
    }
    return "File uploaded";
});

To access the original file name:

request.raw().getPart("file").getSubmittedFileName()

To handle multiple files or parts, I usually have code similar to the following (assuming only files are included in the multi-part encoded upload):

for (Part part : req.raw().getParts()) {
  try (InputStream stream = part.getInputStream()) {
    String filename = part.getSubmittedFileName();
    // save the input stream to the filesystem, and the filename to a database
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM