【问题标题】:Spark (JAVA): how to read and save data file from the http body(Audio file)?Spark(JAVA):如何从 http 正文(音频文件)读取和保存数据文件?
【发布时间】:2016-06-01 06:21:58
【问题描述】:

我有点知道如何从请求中查看数据,但我不确定如何处理它。

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

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

(注意/我跳过了作为 http 标头的前 186 个字节,所以我需要动态地到达那里,而不是硬编码的方式)

【问题讨论】:

    标签: java webserver spark-java


    【解决方案1】:
    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());
    

    上传.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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      相关资源
      最近更新 更多