简体   繁体   English

从发布请求中检索二进制文件

[英]Retrieving binary file from post request

Sending a POST request (Apache httpclient, here Kotlin source code): 发送POST请求(Apache httpclient,此处为Kotlin源代码):

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. 我在发件人处理程序中通过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. request.bodyAsBytes()方法似乎增加了一些字节,因为主体大于原始文件。

Thanks, Jörg 谢谢,约尔格

Near the bottom of Spark's Documentation page there is a section "Examples and FAQ" . Spark的“文档”页面底部附近有一个“示例和常见问题解答”部分 The first example is "How do I upload something?". 第一个示例是“如何上传内容?”。 From there, it links further to an example on GitHub . 从那里,它进一步链接到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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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