public void download(HttpServletRequest request, HttpServletResponse response){
try {
String downloadFilename = "中文.zip";//文件的名称
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
String[] files = new String[]{"http://xxxx/xx.jpg","http://xxx/xx.jpg"};
for (int i=0;i<files.length;i++) {
URL url = new URL(files[i]);
zos.putNextEntry(new ZipEntry(i+".jpg"));
//FileInputStream fis = new FileInputStream(new File(files[i]));
InputStream fis = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
zos.flush();
zos.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
判断服务器上是否有相应的问文件:
String filePath="http://117.51.149.90/videos/"+paramsBean.getEventId()+".mp4";
URL url = new URL(filePath);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
String message = urlcon.getHeaderField(0);
if (StringUtils.hasText(message) && message.startsWith("HTTP/1.1 404")) {
//不存在
map.put("videoPath", "");
}else{
//存在
map.put("videoPath", filePath);
}
判断服务器的方法存在问题:
由于是http地址就相当于每次都要请求服务器 极大的消耗性能和影响查询时间
优化:直接获取地址在服务器那边文件夹直接查询文件是否存在
String filePath = "/home/dc2-user/audi/apache-tomcat-8.5.35/webapps/images/"+fileName+"/" + paramsBean.getEventId() + ".mp4";
File file =new File(filePath);
if(file.exists()) {
map.put("videoPath", filePath);
}else {
map.put("videoPath", "");
}