yijiusmile
2021-05-17 00c11e16ac27b31c8d29b3c64afa88082010c33e
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
232
233
234
package cc.mrbird.febs.common.core.utils;
 
import cc.mrbird.febs.common.core.exception.FebsException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
@Slf4j
public class MyUtil {
 
    public static void downloadFile(File file, HttpServletResponse response) throws IOException {
        try (InputStream fin = new FileInputStream(file); ServletOutputStream out = response.getOutputStream()) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=resume.doc");
 
            byte[] buffer = new byte[1024];
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            log.error("下载文件异常" + e);
            e.printStackTrace();
        }
    }
 
    public static void  download(HttpServletRequest request, HttpServletResponse response, List<File> files , List<String> fileName){
        //设置压缩包的名字
        //解决不同浏览器压缩包名字含有中文时乱码的问题
        String downloadName ="PersonnelInformation-" + DateUtil.format(new Date(), "yyyyMMddhhmmsss") + ".zip";
        String agent = request.getHeader("USER-AGENT");
        try {
            if (agent.contains("MSIE") || agent.contains("Trident")) {
                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
            } else {
                downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
 
 
        //设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            //设置压缩方法
            zipos.setMethod(ZipOutputStream.DEFLATED);
        } catch (Exception e) {
            log.error("设置压缩流出现异常" + e);
            e.printStackTrace();
        }
 
        //循环将文件写入压缩流
        DataOutputStream os = null;
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            try {
                //添加ZipEntry,并ZipEntry中写入文件流
                //这里,加上i是防止要下载的文件有重名的导致下载失败
                zipos.putNextEntry(new ZipEntry(fileName.get(i)));
                os = new DataOutputStream(zipos);
                InputStream is = new FileInputStream(file);
                byte[] b = new byte[100];
                int length;
                while ((length = is.read(b)) != -1) {
                    os.write(b, 0, length);
                }
                is.close();
                zipos.closeEntry();
            } catch (IOException e) {
                log.error("循环将文件写入压缩流出现异常" + e.getMessage());
                e.printStackTrace();
            }
        }
 
        //关闭流
        try {
            os.flush();
            os.close();
            zipos.close();
        } catch (IOException e) {
            log.error("关闭流现异常" + e.getMessage());
            e.printStackTrace();
        }
 
    }
 
    public static Dict filesUpload(MultipartFile file, String uploadPpath, String nextIdStr) throws FebsException, IOException {
        if (file.isEmpty()) {
            throw new FebsException("上传的文件不能为空!请重新上传");
        }
        if (file.getSize() <= 0) {
            throw new FebsException("上传的文件大小需要大于0kb");
        }
        if (file.getSize() > 200 * 1024* 1024) {
            throw new FebsException("上传的文件大于200M");
        }
        if (!FileUtil.exist(uploadPpath)) {
            FileUtil.mkdir(uploadPpath);
        }
        //原本名字
        String fileName = file.getOriginalFilename();
        String suffix = "";
        if (fileName.lastIndexOf(".") > 0) {
            //后缀
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        //生成新的名字
        String newName = nextIdStr + suffix;
        //上传
        file.transferTo(new File(uploadPpath + newName));
        return Dict.create().set("fileName",fileName).set("suffix",suffix).set("newName",newName);
    }
 
    public static Dict filesUpload(MultipartFile file, String uploadPpath) throws FebsException, IOException {
        if (file.isEmpty()) {
            throw new FebsException("上传的文件不能为空!请重新上传");
        }
        if (file.getSize() <= 0) {
            throw new FebsException("上传的文件大小需要大于0kb");
        }
        if (file.getSize() > 200 * 1024* 1024) {
            throw new FebsException("上传的文件大于200M");
        }
        if (!FileUtil.exist(uploadPpath)) {
            FileUtil.mkdir(uploadPpath);
        }
        //原本名字
        String fileName = file.getOriginalFilename();
        String suffix = "";
        if (fileName.lastIndexOf(".") > 0) {
            //后缀
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        if(FileUtil.exist(uploadPpath + fileName)){
            throw  new FebsException("文件已经存在");
        }
 
        //上传
        file.transferTo(new File(uploadPpath + fileName));
        return Dict.create().set("fileName",fileName).set("suffix",suffix);
    }
 
    /**
     *      对字节数组字符串进行Base64解码并生成图片
      */
    public static boolean generateImage(String imgStr,String url) {
        if (imgStr == null) {
            // 图像数据为空
            return false;
        }
        imgStr = imgStr.split(",")[1];
                BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            String imgFilePath = url;
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
 
    /**
     * 将base64字符串,生成文件
     */
    public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
 
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
 
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);
 
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}