我正在尝试从Kaltura下载文件(.mp4),文件超过100mb,以下代码需要花费大量时间才能下载。
还有其他方法可以改善吗?
try {
URL url = new URL("https://www.kaltura.com/p/....");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n = 0;
while (-1 != (n = in.read(buf)))
{
out.write(buf);
}
out.close();
in.close();
res.setContentType("application/octet-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Content-Disposition","attachment;filename=Smac_03_48.mp4 (iPad).mp4");
res.setStatus(200);
res.getOutputStream().write(out.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:2)
问题是ByteArrayOutputStream会大量增长,不时重新分配它的大小。而是立即输出:
TypeCheckingExtension
当然浏览器重定向会更快。
答案 1 :(得分:1)
我尝试使用下面的代码,它按预期工作正常!
URL url = null;
try {
url = new URL(kalturaUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
response.setContentType(httpConn.getContentType());
response.setContentLength(httpConn.getContentLength());
response.setHeader("Content-Disposition", httpConn.getHeaderField("Content-Disposition"));
OutputStream outputStream = response.getOutputStream();
int bytesRead = -1;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
} else {
return "No file to download. Server replied HTTP code: " + httpConn.getResponseCode();
}
httpConn.disconnect();
} catch (MalformedURLException e) {
logger.error("Exception : ",e);
} catch (IOException e) {
logger.error("Exception : ",e);
}