將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:\\";