9
Dosya indirmek için basit bir dinlenme api yazmak istiyorum.java kullanarak indirme dosyası nasıl kıvılcım?
Anladığım kadarıyla dokümanı bulamıyorum Yanıt için mimetype='application/zip'
ayarlamam gerekiyor, ancak akışı nasıl döndüreceğimi belirtmem gerekiyor.
güncelleme: burada çözülmesi örnek kod:
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;
Sadece bir not:: Yalnızca OutputStream kapatıp çiğ HttpServletResponse dönmek gerek hata kodları '4xx' bir istemci hatası değil, genellikle' 5xx' olması gereken bir sunucu hatasıdır. – scrutari