[英]Spark (JAVA): how to read and save data file from the http body(Audio file)?
I kinda know how to see the data from the request, however I'm not sure how to handle it. 我有点知道如何从请求中查看数据,但是我不确定如何处理它。
post("/", (req, res) -> {
System.out.println(req.body());
return "something";
});
which shows me: 这告诉我:
--1Wbh7zeSxsgY0YXI6wHO8nmxeVk4iV
Content-Disposition: form-data; name="file"; filename="1455896241350.m4a"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Data data ... etc
How to get the file attached with the body and save it in the server so later on I could use it? 如何将文件附加到正文中并将其保存在服务器中,以便以后可以使用它?
*------------------------ * ------------------------ * ------------------------* * ------------------------ * ------------------------ * ------------------------ *
I've tired this code: 我已经厌倦了这段代码:
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");
it worked fine for me, but it is static or hard-coded, I need it dynamic. 它对我来说很好用,但是它是静态的或硬编码的,我需要动态的。
(Note/ I skiped the first 186 bytes which are the header of the http, so I need to get there dynamically not the hard-coded way) (注/我跳过了前186个字节,它们是http的标头,因此我需要动态到达那里而不是硬编码方式)
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 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>
please excuse the hacky exception handling 请原谅骇客的异常处理
this requires Spark 2.3 这需要Spark 2.3
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.3</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.