springboot 实现ftp上的多个文件打包成zip下载

将ftp文件保存到服务器本地,并得到本地文件的File对象

String baseFileName = forecast.getMainBillAttach().substring(forecast.getMainBillAttach().lastIndexOf("/") + 1,forecast.getMainBillAttach().length());
//获取文件类型,由于ftp上传中文名称的内容会乱码,所以这里将文件名转为base64,路径使用这个,想要找文件名的时候,在将这个转换回来即可
String fileName = Hex.hexStr2Str(baseFileName);
if(fileName.indexOf(".") !=-1){
String type = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String path = ZipPackerUtil.realPath+ZipPackerUtil.FILE_PACKAGE+forecast.getMainNo()+type; //下载到服务器的路径与文件名
ZipPackerUtil.downloadFile(forecast.getMainBillAttach(), path);
fs[j++] = new File(path);
1
2
3
4
5
6
7
8
创建zip的输出流,并将上面得到的file对象,转换为输入流,将文件写入zip输出流中返回给前端

ZipOutputStream os = new ZipOutputStream(resposne.getOutputStream());
BufferedInputStream bis = null;
try {
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr=sdf.format(date);
resposne.setHeader("Content-Disposition", "attachment; filename="+dateStr+".zip");
resposne.setContentType("application/octet-stream; charset=GBK");
for(int i=0;i<fs.length;i++) {
if(fs[i]!=null){
FileInputStream fis = null;
fis = new FileInputStream(fs[i]);
ZipEntry z=new ZipEntry(fs[i].getName());
os.putNextEntry(z);
int len;
//读入需要下载的文件的内容,打包到zip文件
while((len = fis.read(buffer))>0) {
os.write(buffer,0,len);
}
}
}
os.flush();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
这里注意我前端是有form形式,action访问接口,而返回值为文件,所以需要在返回前,设置头信息

resposne.setHeader("Content-Disposition", "attachment; filename="+dateStr+".zip");
resposne.setContentType("application/octet-stream; charset=GBK");
1
2
这个是上面下载文件时用的下载方法

public synchronized static void downloadFile(String remoteFilePath, String localFilePath)
{
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
try
{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());//
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1)
{
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bis.close();
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
这是其中用到的常量,包括地址以及存储路径和文件名

/**
* 存放ZIP的临时文件夹
*/
public static final String ZIP_PACKAGE = "temporary_zip";
/**
* 存放file文件的临时文件夹
*/
public static final String FILE_PACKAGE = "主单文件_";
/**
* zip存放 根目录
*/
public static final String realPath = "D:\\";

posted @ 2019-09-02 19:16  李艳艳665  阅读(1742)  评论(0编辑  收藏  举报