2016-02-19 74 views
1

我有點知道如何查看請求中的數據,但我不知道如何處理它。Spark(JAVA):如何從http正文(音頻文件)中讀取和保存數據文件?

post("/", (req, res) -> { 
     System.out.println(req.body()); 
     return "something"; 
    }); 

這表明我:

--1Wbh7zeSxsgY0YXI6wHO8nmxeVk4iV 
Content-Disposition: form-data; name="file"; filename="1455896241350.m4a" 
Content-Type: application/octet-stream 
Content-Transfer-Encoding: binary 

Data data ... etc 

如何獲得附加與身體的文件並將其保存在服務器,以便以後我可以用它?

* ------------------------ * -------------------- ---- * ------------------------ *

我已經厭倦了這樣的代碼:

try { 
     FileOutputStream fis = new FileOutputStream(new File("audio.m4a")); 
     System.out.println("file created"); 
     try { 
      int offset = 186; 
      fis.write(req.bodyAsBytes(), offset, req.bodyAsBytes().length - offset); 
      fis.close(); 
      System.out.println("file wrote"); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    System.out.println("done"); 

它的工作對我來說很好,但它是靜態的或硬編碼的,我需要它動態的。

(注/ I skiped第186個字節,這是HTTP的頭,所以我需要到那裏動態而不是硬編碼方式)

回答

0
get("/upload", (request, response) -> { 
    return new ModelAndView(null, "upload.ftl"); 
}, new FreeMarkerEngine()); 

post("/upload", "multipart/form-data", ((request, response) -> { 
    try { 
     request.raw().setAttribute("org.eclipse.jetty.multipartConfig", 
      new MultipartConfigElement("/tmp", 100000000, 100000000, 1024)); 

     String filename = request.raw().getPart("file").getSubmittedFileName(); 

     Part uploadedFile = request.raw().getPart("file"); 
     try (final InputStream in = uploadedFile.getInputStream()) { 
      Files.copy(in, Paths.get("/tmp/"+filename)); 
     } 
     uploadedFile.delete(); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 

    return new ModelAndView(null, "upload.ftl"); 
}), new FreeMarkerEngine()); 

upload.ftl

<form action="/upload" enctype="multipart/form-data" method="post"> 
    <label for="file">File to send</label> 
    <input type="file" name="file"><br> 
    <input type="submit" value="Upload"> 
</form> 

請原諒哈克異常處理

這需要星火2.3

<dependency> 
    <groupId>com.sparkjava</groupId> 
    <artifactId>spark-core</artifactId> 
    <version>2.3</version> 
</dependency> 
相關問題