0

发送 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()

我通过 spark-java 请求对象在我的 post 处理程序中收到请求。如何从发布请求中检索原始文件(加上文件名作为奖励)?request.bodyAsBytes() 方法似乎添加了一些字节,因为正文比原始文件大。

谢谢,约尔格

4

1 回答 1

0

在 Spark 文档页面的底部附近有一个“示例和常见问题解答”部分。第一个例子是“我如何上传东西?”。从那里,它进一步链接到GitHub 上的示例

简而言之:

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";
});

要访问原始文件名:

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

为了处理多个文件或部分,我通常有类似于以下的代码(假设只有文件包含在多部分编码上传中):

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
  }
}
于 2017-10-04T14:09:04.543 回答