派生自 projectDept/qhighschool

EricsHu
2023-11-24 691f717df93c32d89b13f7f73f0678441d60c840
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
package com.qxueyou.scc.controller;
 
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
 
//import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSSException;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectResult;
import com.qxueyou.scc.base.model.CacheConstants;
import com.qxueyou.scc.base.model.FileMeta;
import com.qxueyou.scc.base.model.Result;
import com.qxueyou.scc.base.util.ClientUtils;
import com.qxueyou.scc.base.util.UUIDUtils;
import com.qxueyou.scc.teach.res.service.HweiYunOBSService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;
import java.util.Map;
 
/**
 * @ClassName: ObsController
 * @Description: OBS服务器Controller
 * @Author: wuhuiju
 * @Date: 2021-12-21 15:20
 * @Version: 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/file")// @RequestMapping("/file")
public class HweiYunOBSController {
    private final Logger log = LogManager.getLogger("FileController");
 
    @Resource
    private HweiYunOBSService hweiYunOBSService;
 
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public List<FileMeta> save(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
 
        if (ObjectUtils.isEmpty(file) || file.getSize() <= 0) {
            return null;
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.indexOf(".")+1);
 
        StringBuffer path=new StringBuffer();
        //识别文件后缀格式,获取对应的文件存储路径
        String pathFile = CacheConstants.fileFormatMap.get(substring.toUpperCase(Locale.ROOT));
        if (StringUtils.isEmpty(pathFile)) {//如果为空则上传到默认存储文件夹
            path.append(CacheConstants.GUANGXI_ACQUIESCE);
        }else{
            path.append(pathFile);
        }
        String uuid = UUIDUtils.UUID();
        //将文件重新命名,防止出现重名覆盖
        String newFilename=uuid.concat(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        final List<FileMeta> test = hweiYunOBSService.fileUpload(file,path.append(newFilename).toString());
//        return ResponseVO.ok("执行成功",test);
        return test;
    }
 
    /**
     * 文件上传接口:为客户端提供多线程分片上传接口
     * 返回状态值:200代表成功,500代表上传失败,205代表需重新尝试
     *
     * @param identifier 唯一id,需客户端保证唯一性,相同文件保证唯一即可,非MD5
     * @return
     * @TODO : 目前缺少对 各模块文件个数、文件格式、文件大小的上传控制,统一增加在configFileModule表里面即可实现 1 图片; 2 文档 3 视频 4 音频
     */
    @RequestMapping(value = "/uploadChunk", headers = "content-type=multipart/*", method = RequestMethod.POST)
    public @ResponseBody FileMeta doUploadPublic(MultipartFile file, HttpServletResponse response,
                            Integer chunkNumber, Integer totalChunks, long chunkSize, long totalSize, String identifier, String filename, Integer currentChunkSize) {
 
        FileMeta fileMeta = new FileMeta();
        try {
 
            Result uploadResult = null;
 
            uploadResult = hweiYunOBSService.uploadChunk(file.getInputStream(), identifier.concat(ClientUtils.getUserId()), chunkNumber, currentChunkSize, totalChunks, filename);
 
 
            fileMeta.setFileId(uploadResult.getDataT("fileId"));
            fileMeta.setPath(uploadResult.getDataT("path"));
 
            if (!uploadResult.isSuccess()) {
                response.setStatus(205);
            }
 
        } catch (OSSException e) {
            response.setStatus(500);
            log.error(e, e);
        } catch (Exception e) {
            log.error("上传模块解析出错:" + e.getMessage(), e);
            response.setStatus(500);
        }
 
        fileMeta.setFileName(filename);
        fileMeta.setFileSize(String.valueOf(totalSize));
        fileMeta.setFileType(null);
 
        return fileMeta;
    }
 
    /**
     * 初始化分片上传任务
     *
     * @return
     */
    @RequestMapping(value = "/uploadChunk/init", method = RequestMethod.POST)
    public @ResponseBody
    Result initUploadChunk(String identifier, String fileName,String md5) {
 
        //如果MD5的对应文件存在则直接返回
//        Result result = fileService.checkMd5(md5,fileName);
        String substring = fileName.substring(fileName.indexOf(".")+1);
 
        StringBuffer path=new StringBuffer();
        //识别文件后缀格式,获取对应的文件存储路径
        String pathFile = CacheConstants.fileFormatMap.get(substring.toUpperCase(Locale.ROOT));
        if (StringUtils.isEmpty(pathFile)) {//如果为空则上传到默认存储文件夹
            path.append(CacheConstants.GUANGXI_ACQUIESCE);
        }else{
            path.append(pathFile);
        }
        String uuid = UUIDUtils.UUID();
        //将文件重新命名,防止出现重名覆盖
        String newFilename=uuid.concat(String.valueOf(fileName.lastIndexOf(".")));
        return hweiYunOBSService.initUploadChunk(identifier.concat(ClientUtils.getUserId()),path.append(newFilename).toString(),md5);
 
    }
 
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Result delete(@RequestParam(value = "fileName", required = false)  String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return new Result(false,"删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileName);
        return delete?new Result(true,"success"):new Result(false,"删除失败");
    }
 
    @RequestMapping(value = "deletes", method = RequestMethod.POST)
    //@RequestParam 获取List,数组则不需要
    public Result delete(@RequestParam("fileNames") List<String> fileNames) {
        if (ArrayUtil.isEmpty(fileNames)) {
            return new Result(false,"删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileNames);
        return delete?new Result(true,"success"):new Result(false,"删除失败");
    }
 
 
    @RequestMapping(value = "download", method = RequestMethod.POST)
    public Result download(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileName", required = false) String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return new Result(false,"下载文件为空");
        }
        try (
                InputStream inputStream = hweiYunOBSService.fileDownload(fileName);
             BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())){
            if(inputStream == null) {
                return new Result(false);
            }
            // 为防止 文件名出现乱码
            final String userAgent = request.getHeader("USER-AGENT");
            // IE浏览器
            if (StrUtil.contains(userAgent, "MSIE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                // google,火狐浏览器
                if (StrUtil.contains(userAgent, "Mozilla")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    // 其他浏览器
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
            }
            response.setContentType("application/x-download");
            // 设置让浏览器弹出下载提示框,而不是直接在浏览器中打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            IoUtil.copy(inputStream, outputStream);
            return null;
        } catch (IOException | ObsException e) {
            return new Result(false);
        }
    }
}