zjh
2024-12-30 1b7ed7edb09aaecf68ddf3396ee007bc6eadf52a
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package com.ltkj.web.config.captcha;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.domain.entity.SysDictData;
import com.ltkj.common.utils.SnowFlake;
import com.ltkj.common.utils.uuid.UUID;
import com.ltkj.hosp.domain.SysAttachment;
import com.ltkj.hosp.service.ISysAttachmentService;
import com.ltkj.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ltkj.common.config.ltkjConfig;
import com.ltkj.common.constant.Constants;
import com.ltkj.common.core.domain.AjaxResult;
import com.ltkj.common.utils.StringUtils;
import com.ltkj.common.utils.file.FileUploadUtils;
import com.ltkj.common.utils.file.FileUtils;
import com.ltkj.framework.config.ServerConfig;
 
/**
 * 通用请求处理
 *
 * @author ltkj
 */
@RestController
@RequestMapping("/common")
@Api(tags = "文件上传接口大全")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
 
    @Autowired
    private ServerConfig serverConfig;
 
    private static final String FILE_DELIMETER = ",";
 
    @Value("${photoPath}")
    String photoPath;
 
    @Value("${photoServer}")
    String photoServer;
 
    @Value("${ltkj.profile}")
    String path;
    @Autowired
    private ISysAttachmentService sysAttachmentService;
    @Autowired
    private ISysDictDataService sysDictDataService;
 
 
    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = ltkjConfig.getDownloadPath() + fileName;
 
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
 
    /**
    *   重新写的上传图片   适用于体检套餐
    */
    @PostMapping("/packageUpload")
    public AjaxResult packageUpload(@RequestBody MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //新文件名
        fileName = UUID.randomUUID() + suffixName;
        //文件全路径名
        File dest = new File(photoPath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        AjaxResult ajax = AjaxResult.success();
        String url=photoServer + fileName;
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        return ajax;
    }
 
    /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    @ApiOperation(value = "通用文件上传")
    public AjaxResult uploadFile(@RequestPart("file") MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = ltkjConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            //ajax.put("filePath", path+fileName);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    @PostMapping("/uploadImgExe")
    @ApiOperation(value = "EXE程序循环读取图片上传")
    public AjaxResult uploadImgExe(@RequestPart("file") MultipartFile file,@RequestParam("val")String dictVal,@RequestParam("ip")String ip){
        try {
            // 上传文件路径
            String filePath = ltkjConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            //ajax.put("filePath", path+fileName);
            ajax.put("fileName", fileName);
            final String newFileName = FileUtils.getName(fileName);
            ajax.put("newFileName", newFileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            SysAttachment sysAttachment = new SysAttachment();
            sysAttachment.setId(SnowFlake.getInstance().nextId());
            sysAttachment.setFileName(newFileName);
            sysAttachment.setFilePath(fileName);
            sysAttachment.setUrl(url);
            sysAttachment.setSysDictVal(dictVal);
            sysAttachment.setIp(ip);
            final Map<String, String> map = FileUploadUtils.getFileSize(file);
            sysAttachment.setFileSize(map.get("fileSizeBytes"));
            sysAttachment.setFileSizeMb(map.get("fileSizeMB"));
            sysAttachment.setFileSizeGb(map.get("fileSizeGB"));
            sysAttachmentService.insertSysAttachment(sysAttachment);
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
 
    @GetMapping("/listExeVal")
    public AjaxResult listExeDictVal(){
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDictType,"sys_exe_img_type");
        final List<SysDictData> list = sysDictDataService.list(queryWrapper);
        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        for (SysDictData sysDictData : list) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("label",sysDictData.getDictLabel());
            hashMap.put("value",sysDictData.getDictValue());
            hashMaps.add(hashMap);
        }
        return AjaxResult.success().put("data",hashMaps);
    }
 
    @GetMapping("/uploadFile")
    @ApiOperation(value = "通用文件上传base64")
    public AjaxResult uploadFiles(@ApiParam(value = "参数")String file){
        log.info(file);
        return AjaxResult.success(file);
    }
 
 
    /**
     * 通用上传请求(多个)
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = ltkjConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = ltkjConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
 
 
    @DeleteMapping("/deletedFile")
    @ApiOperation(value = "通用文件删除接口")
    public AjaxResult deletedFile(@RequestParam String url) {
        //文件后缀
        File files=new File(url);
        String name = files.getName();
        File file=new File(photoPath+name);
        if (file.exists()) {
            if(file.delete()){
                return AjaxResult.success("删除成功");
            }
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success("删除成功");
    }
}