springboot單,多檔案打包下載到客戶端--工具類
阿新 • • 發佈:2019-09-24
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*檔案下載匯出
*/
public class ZipFileExport {
/**
* 檔案匯出下載到----客戶端
* @param response
* @param filename
* @param path
*/
public void downImgClient(HttpServletResponse response, String filename, String path ){
if (filename != null) {
FileInputStream inputStream = null;
BufferedInputStream bs = null;
ServletOutputStream servletOutputStream = null;
try {
response.setHeader("Content-Type","application/octet-stream");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
File file = new File(path);
inputStream = new FileInputStream(file);
bs =new BufferedInputStream(inputStream);
servletOutputStream = response.getOutputStream();
writeBytes(bs, servletOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
//servletOutputStream = null;
}
if (bs!=null){
bs.close();
}
if (inputStream != null) {
inputStream.close();
//inputStream = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//writeBytes()構造方法
private void writeBytes(InputStream in, OutputStream out) throws IOException {
byte[] buffer= new byte[1024];
int length = -1;
while ((length = in.read(buffer))!=-1){
out.write(buffer,0,length);
}
in.close();
out.close();
}
/**
* 單檔案匯出下載
* @param response
* @param filename
* @param path
*/
public void downImg(HttpServletResponse response, String filename, String path ){
if (filename != null) {
FileInputStream is = null;
BufferedInputStream bs = null;
OutputStream os = null;
try {
File file = new File(path);
if (file.exists()) {
is = new FileInputStream(file);
bs =new BufferedInputStream(is);
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = bs.read(buffer)) != -1){
os.write(buffer,0,len);
}
}else{
String error = "下載的檔案資源不存在";
System.out.println(error);
}
}catch(IOException ex){
ex.printStackTrace();
}finally {
try{
if(is != null){
is.close();
}
if( bs != null ){
bs.close();
}
if( os != null){
os.flush();
os.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
downImgClient(response,filename,path);
}
}
/**
* 多檔案打包下載
* @param response
* @param names 檔名集合
* @param paths 檔案路徑集合
* @param directoryPath //臨時存放--伺服器上--zip檔案的目錄
*/
public void FileDownload(HttpServletResponse response, List<String> names, List<String> paths,String directoryPath,String zipFileNameEn) {
File directoryFile=new File(directoryPath);
if(!directoryFile.isDirectory() && !directoryFile.exists()){
directoryFile.mkdirs();
}
//設定最終輸出zip檔案的目錄+檔名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String zipFileName =zipFileNameEn+ formatter.format(new Date())+".zip";
String strZipPath = directoryPath+"/"+zipFileName;
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
File zipFile = new File(strZipPath);
try{
//構造最終壓縮包的輸出流
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i<paths.size() ;i++){
//解碼獲取真實路徑與檔名
String realFileName = java.net.URLDecoder.decode(names.get(i),"UTF-8");
String realFilePath = java.net.URLDecoder.decode(paths.get(i),"UTF-8");
File file = new File(realFilePath)
if(file.exists())
{
zipSource = new FileInputStream(file);//將需要壓縮的檔案格式化為輸入流
/**
* 壓縮條目不是具體獨立的檔案,而是壓縮包檔案列表中的列表項,稱為條目,就像索引一樣這裡的name就是檔名,
* 檔名和之前的重複就會導致檔案被覆蓋
*/
ZipEntry zipEntry = new ZipEntry(realFileName);//在壓縮目錄中檔案的名字
zipStream.putNextEntry(zipEntry);//定位該壓縮條目位置,開始寫入檔案到壓縮包中
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
byte[] buf = new byte[1024 * 10];
while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
{
zipStream.write(buf, 0, read);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉流
try {
if(null != bufferStream) {
bufferStream.close();
}
if(null != zipStream){
zipStream.flush();
zipStream.close();
}
if(null != zipSource){
zipSource.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//判斷當前壓縮檔案是否生成存在:true-把該壓縮檔案通過流輸出給客戶端後刪除該壓縮檔案
if(zipFile.exists()){
//傳送給客戶端
downImgClient(response,zipFileName,strZipPath);
//刪除本地儲存的檔案
zipFile.delete();
}
}
}