java从网络下载多个文件
首先是打包下载多文件,即打成压缩包在下载。
其次 别处的资源:可以是别的服务器,可以是网上的资源,当然也可以是本地的(更简单)
最后:一次性下载,一次性下载多个文件
三步走:
一、先将 “别处” 需要下载的文件下载到服务器,然后将文件的路径改掉
二、然后将服务器上的文件打成压缩包
三、下载这个压缩包
//下载
@RequestMapping("/download01")
public void downloadImage(String tcLwIds, HttpServletRequest request, HttpServletResponse response) throws Exception{
boolean dflag = false;
String[] paths = tcLwIds.split(",");
File [] file1 = new File[paths.length];
DownLoadImageUtil imageUtils = new DownLoadImageUtil();
if(paths.length > 1){
for (int i = 0; i < paths.length; i++) {
String imagepath=paths[i];
imageUtils.makeImage(imagepath); //将url的图片下载到本地,这个方法在下边
//修改为图片存放路径
file1[i] = new File("D:/upload/"+imagepath.substring(imagepath.lastIndexOf("/")));
}
filesDown(request, response, file1);//这是下边的一个方法
}
}
//将下载到 服务器 的图片 放入压缩包
public void filesDown(HttpServletRequest request,HttpServletResponse response,File[] file1 ) throws Exception {
Random r=new Random();
String tmpFileName =r.nextInt(10000) +"downImage.zip";
String upath=request.getRealPath("/");
upath=upath.substring(0,upath.length()-1);
upath=upath.substring(0,upath.lastIndexOf("\\"));
//服务地址的存放路径
String FilePath = upath+"/ROOT/data/";
File f=new File(FilePath);
if(!f.exists()){ //路径不存在就创建
FileUtil.createDir(FilePath);
}
byte[] buffer = new byte[1024];
String strZipPath = FilePath + tmpFileName; //路径加文件名
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
for (int i = 0; i < file1.length; i++) {
FileInputStream fis = new FileInputStream(file1[i]);
out.putNextEntry(new ZipEntry(file1[i].getName()));
//设置压缩文件内的字符编码,不然会变成乱码
out.setEncoding("GBK");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
//下载的服务地址根据实际情况修改
boolean dflag = downloafile(request, response,"http://localhost:8080/data/"+tmpFileName);
//将服务器上 压缩前的源文件 删除
for (int i = 0; i < file1.length; i++) {
if (file1[i].isFile()) {
file1[i].delete();
}
}
//将服务器上的压缩包删除
File fileZip=new File(strZipPath);
fileZip.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
//写到本地
public boolean downloafile(HttpServletRequest request,HttpServletResponse response, String path) {
String name = path.substring(path.lastIndexOf("/")+1);
String filename = DownLoadImageUtil.encodeChineseDownloadFileName(request, name);
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ";");
boolean flag = false;
try {
URL url = new URL(path);
InputStream inStream = url.openConnection().getInputStream();
BufferedInputStream in = new BufferedInputStream(inStream);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
ServletOutputStream os = response.getOutputStream();
os.write(out.toByteArray());
os.flush();
os.close();
flag = true;
} catch (Exception e) {
logger.error("违法信息下载...出错了");
}
return flag;
}
makeImage(); 方法(如果是服务器上的图片,可以省略这一步,直接打包)
/**
* 下载图片,并按照指定的路径存储
* @param bean
* @param filePath
*/
public void makeImage( String filePath) {
// 网络请求所需变量
try {
//new一个URL对象
URL url = new URL(filePath);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
byte []data=outStream.toByteArray();
//先将图片从url下载到服务器的D:/upload/
File imageFile = new File("D:/upload/"+filePath.substring(filePath.lastIndexOf("/")));
//创建输出流
FileOutputStream foutStream = new FileOutputStream(imageFile);
foutStream.write(data);
//关闭输出流
foutStream.close();
inStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}