我想为文件下载编写简单的rest api。
我无法找到有关它的文档,因为我知道我需要为响应设置mimetype='application/zip'
,但不清楚如何返回流。
更新: 解决了这里的示例代码:
public static void main(String[] args) {
//setPort(8080);
get("/hello", (request, responce) -> getFile(request,responce));
}
private static Object getFile(Request request, Response responce) {
File file = new File("MYFILE");
responce.raw().setContentType("application/octet-stream");
responce.raw().setHeader("Content-Disposition","attachment; filename="+file.getName()+".zip");
try {
try(ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(responce.raw().getOutputStream()));
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)))
{
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = bufferedInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer,0,len);
}
}
} catch (Exception e) {
halt(405,"server error");
}
return null;
答案 0 :(得分:9)
您需要的内容与this thread类似。您只需要关闭OutputStream并返回原始HTTPServletResponse:
try {
...
zipOutputStream.flush();
zipOutputStream.close();
} catch (Exception e) {
halt(405,"server error");
}
return responce.raw();