Spark(JAVA):如何从http体(音频文件)中读取和保存数据文件?

时间:2016-02-19 15:51:28

标签: java webserver spark-java

我知道如何查看请求中的数据,但我不知道如何处理它。

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

它对我来说很好,但它是静态的或硬编码的,我需要它是动态的。

(注意/我滑了前186个字节,这是http的标题,所以我需要动态到达而不是硬编码的方式)

1 个答案:

答案 0 :(得分: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>

请原谅hacky异常处理

这需要Spark 2.3

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.3</version>
</dependency>