簡體   English   中英

從發布請求中檢索二進制文件

[英]Retrieving binary file from post request

發送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的“文檔”頁面底部附近有一個“示例和常見問題解答”部分 第一個示例是“如何上傳內容?”。 從那里,它進一步鏈接到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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM