管道基础大数据平台系统开发-【后端】-Server
1
13693261870
2022-10-11 a47aa433d7a54910351ecca27b44a539653eab35
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
package com.lf.server.service.all;
 
import com.lf.server.controller.all.BaseController;
import com.lf.server.entity.all.ResponseMsg;
import com.lf.server.entity.sys.AttachEntity;
import com.lf.server.entity.sys.UserEntity;
import com.lf.server.helper.PathHelper;
import com.lf.server.service.sys.AttachService;
import com.sun.xml.internal.fastinfoset.tools.XML_SAX_StAX_FI;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
 
/**
 * 文件服务类
 * @author WWW
 */
@Service
public class FileService {
    @Autowired
    PathHelper pathHelper;
 
    @Autowired
    AttachService attachService;
 
    private static long MAX_FILE_SIZE = 20 * 1024 * 1024;
 
    private final static Log log = LogFactory.getLog(FileService.class);
 
    public ResponseMsg<String> upload(UserEntity ue, String tab, MultipartFile file, BaseController ctrl) {
        try {
            if (file == null && file.isEmpty()) {
                return ctrl.fail("文件上传为空", null);
            }
            if (file.getSize() > MAX_FILE_SIZE) {
                return ctrl.fail(String.format("文件大于 %d MB", MAX_FILE_SIZE / 1024 / 1024), null);
            }
 
            // 传输文件
            String oldName = file.getOriginalFilename();
            String filePath = pathHelper.getConfig().getTempPath() + File.separator + oldName;
            File newFile = new File(filePath);
            file.transferTo(newFile);
 
            // 获取MD5
            String md5 = getFileMd5(filePath);
            AttachEntity entity = attachService.selectByGuid(md5);
            if (entity != null) {
                newFile.delete();
                return ctrl.success("文件已存在", md5);
            }
 
            String uploadPath = pathHelper.getUploadFullPath();
            String targetPath = uploadPath + File.separator + md5;
            newFile.renameTo(new File(targetPath));
 
            AttachEntity ae = getAttachEntity(ue, tab, oldName, md5);
            int rows = attachService.insert(ae);
 
            return rows > 0 ? ctrl.success(md5) : ctrl.fail("保存文件失败", null);
        } catch (Exception ex) {
            return ctrl.fail(ex.getMessage(), null);
        }
    }
 
    private String getFileMd5(String filePath) throws IOException {
        FileInputStream fileStream = new FileInputStream(filePath);
        String md5 = DigestUtils.md5Hex(fileStream);
        fileStream.close();
 
        return md5;
    }
 
    protected AttachEntity getAttachEntity(UserEntity ue, String tab, String oldName, String md5) {
        AttachEntity entity = new AttachEntity();
        entity.setName(oldName);
        entity.setTab(tab);
        entity.setGuid(md5);
        String subPath = PathHelper.getUploadPath() + File.separator + md5;
        entity.setPath(subPath);
        if (ue != null) {
            entity.setCreateUser(ue.getId());
        }
 
        return entity;
    }
 
    /**
     * 上传文件
     *
     * @param req
     * @param res
     */
    public void upload(HttpServletRequest req, HttpServletResponse res) {
        try {
            // 处理中文乱码问题
            req.setCharacterEncoding("utf-8");
            res.setContentType("text/html;charset=utf-8");
 
            // 检查请求是/否是multipart/form-data类型
            if (!ServletFileUpload.isMultipartContent(req)) {
                throw new RuntimeException("表单的enctype属性不是multipart/form-data类型!!");
            }
 
            // 创建上传所需要的两个对象:磁盘文件对象+文件上传对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);
            ServletRequestContext ctx = new ServletRequestContext(req);
 
            //限制单个文件的大小
            sfu.setFileSizeMax(1024 * 10);
 
            //限制上传的总文件大小
            sfu.setSizeMax(1024 * 200);
 
            // 设置编码方式
            sfu.setHeaderEncoding("utf-8");
 
            // list容器用来保存表单中的所有数据信息
            List<FileItem> items = sfu.parseRequest(ctx);
 
            // 遍历容器,处理解析的内容:一个处理普通表单域,一个处理文件的表单域
            for (FileItem item : items) {
                if (item.isFormField()) {
                    handleFormField(item);
                } else {
                    handleFileField(item, req);
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage() + ex.getStackTrace() + "\n");
        }
    }
 
    /**
     * 处理 普通数据项
     *
     * @param item
     */
    private void handleFormField(FileItem item) {
        // 获取 普通数据项中的 name值
        String fieldName = item.getFieldName();
 
        // 获取 普通数据项中的 value值
        String value = "";
        try {
            // 以 utf-8的编码格式来解析 value值
            value = item.getString("utf-8");
        } catch (Exception ex) {
            log.error(ex.getMessage() + ex.getStackTrace() + "\n");
        }
 
        // 输出到控制台
        System.out.println("fieldName:" + fieldName + "--value:" + value);
    }
 
    /**
     * 处理 文件数据项
     *
     * @param item
     */
    private void handleFileField(FileItem item, HttpServletRequest req) {
        // 获取 文件数据项中的 文件名
        String fileName = item.getName();
 
        // 判断 此文件的文件名是否合法
        if (fileName == null || "".equals(fileName)) {
            return;
        }
 
        // 控制只能上传图片
        String img = "image";
        if (!item.getContentType().startsWith(img)) {
            return;
        }
 
        // 将文件信息输出到控制台:文件名+文件大小
        System.out.println("fileName:" + fileName);
        System.out.println("fileSize:" + item.getSize());
 
        // 获取 当前项目下的 /files 目录的绝对位置
        ServletContext ctx = req.getSession().getServletContext();
        String path = ctx.getRealPath("/files");
 
        // 创建 file对象
        File file = new File(path);
        if (!file.exists()) {
            // 创建目录
            file.mkdir();
        }
 
        // 将文件保存到服务器上(UUID是通用唯一标识码)
        try {
            item.write(new File(file.toString(), UUID.randomUUID() + "_" + fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}