ke
2024-07-19 08a962d2925baa255207fdf979e6fee794f1773b
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package cn.gistack.sm.sjztmd.util;
 
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonArray;
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
 
public  class DownloadZipUtils {
    //private static Logger logger = LoggerFactory.getLogger(Test.class);
    /**
     * 需要压缩的文件夹
     */
    private final static String downloadDir = "download";
    /**
     * 打包后的文件夹
     */
    private final static String downloadZip = "downloadZip";
 
 
    public static HttpServletRequest request;
 
    public static HttpServletResponse response;
 
    /**
     *
     * @param urls
     * @return 获取url
     */
 
    public static List<String> getUrls(List<String> urls){
 
        List<String> urlss = new ArrayList<>();
        for (String url : urls) {
 
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(url, JsonArray.class);
 
            //解析json数据提取ur
            for (JsonElement element : jsonArray) {
                JsonObject jsonObject = element.getAsJsonObject();
                String urlsss = jsonObject.get("url").getAsString();
                urlss.add(urlsss);
            }
        }
        return urlss;
    }
 
 
 
 
 
 
    /**
     * 通过图片url下载图片到指定文件夹
     * @param downloadUrl    图片url
     */
    public static void  downloadFile(String downloadUrl ) {
 
 
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //获取连接
            URL url=new URL(downloadUrl);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //连接超时时间
            //connection.setConnectTimeout(3*1000);
            //设置请求头
            //connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            //获取输入流
            inputStream=connection.getInputStream();
            //System.out.println("竟来了");
            File fileDir=new File(downloadDir);
            if(!fileDir.exists()){//如果文件夹不存在
                fileDir.mkdir();//创建文件夹
            }
 
            //截取文件名称
            String filePath = downloadDir+"/" + downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            //System.out.println(filePath);
            File file = new File(filePath);
            file.createNewFile();//创建文件,存在覆盖
 
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[16384];
            while ((len = inputStream.read(buf, 0, 16384)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            //logger.error("文件下载出错:" + e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                //logger.error("关闭流出错:" + e);
            }
        }
    }
 
 
    /**
     * 下载压缩包
     */
    public static void downloadZip(HttpServletRequest request, HttpServletResponse res,Integer  logoType) throws IOException {
        OutputStream out = null;
        File zip = null;
        String zipName;
        try{
            //多个文件进行压缩,批量打包下载文件
            //创建压缩文件需要的空的zip包
            if (logoType==1) {
                zipName="水库白蚁防治图片视频资料.zip";
            }else {
                zipName="堤坝白蚁防治图片视频资料.zip";
            }
 
            String zipFilePath = downloadZip+File.separator+zipName;
 
            File fileDir=new File(downloadZip);
            if(!fileDir.exists()){//如果文件夹不存在
                fileDir.mkdir();//创建文件夹
            }
 
            //压缩文件
            zip = new File(zipFilePath);
            zip.createNewFile();//创建文件,存在覆盖
 
            //创建zip文件输出流
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
            zipFile(downloadDir, zos);
            zos.close();
 
            //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            bis.close();
 
            //IO流实现下载的功能
            res.setCharacterEncoding("UTF-8"); //设置编码字符
            res.setContentType("application/json;charset=utf-8"); //设置下载内容类型application/octet-stream(二进制流,未知文件类型);
 
            //防止文件名乱码
            String userAgent = request.getHeader("USER-AGENT");
            if (userAgent.contains("Firefox") || userAgent.contains("firefox")) {//火狐浏览器
                zipName = new String(zipName.getBytes(), "ISO8859-1");
            } else {
                zipName = URLEncoder.encode(zipName, "UTF-8");//其他浏览器
            }
 
            res.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
            out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框
            out.write(buff);//输出数据文件
            //System.out.println("压缩包下载完成");
        }catch(Exception e) {
            //logger.error("压缩包下载出错:" + e);
        }finally {
            if(out != null){
                out.flush();//释放缓存
                //out.close();//关闭输出流
            }
 
            //下载完后删除文件夹和压缩包
            File fileDir = new File(downloadDir);
            FileUtils.deleteDirectory(fileDir);
 
            if(zip != null){
                zip.delete();
            }
        }
    }
 
    /**
     * 压缩文件
     * @param filePath    需要压缩的文件夹
     * @param zos    zip文件输出流
     */
    private static void zipFile(String filePath, ZipOutputStream zos) throws IOException {
        File inputFile = new File(filePath);  //根据文件路径创建文件
        if(inputFile.exists()) { //判断文件是否存在
            if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹
                //创建输入流读取文件
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
 
                //将文件写入zip内,即将文件进行打包
                zos.putNextEntry(new ZipEntry(inputFile.getName()));
 
                //写入文件的方法,同上
                int size = 0;
                byte[] buffer = new byte[16384];  //设置读取数据缓存大小
                while ((size = bis.read(buffer)) > 0) {
                    zos.write(buffer, 0, size);
                }
                //关闭输入输出流
                zos.closeEntry();
                bis.close();
 
            } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip
                try {
                    File[] files = inputFile.listFiles();
                    for (File fileTem:files) {
                        zipFile(fileTem.toString(),zos);
                    }
                } catch (Exception e) {
                    //logger.error("压缩文件出错:" + e);
                }
            }
        }
    }
}