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

发送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 Request-object在我的邮件处理程序中收到请求。 如何从发布请求中检索原始文件(加上文件名称作为奖励)? request.bodyAsBytes()方法似乎增加了一些字节,因为正文大于原始文件。

谢谢,约尔格

在Spark的Documentation页面的底部,有一个“Examples and FAQ”部分 。 第一个例子是“如何上传东西?”。 从那里,它进一步链接到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 } }