rk
2026-03-23 6cfc2e4258089c953b67054229170c1178585590
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.doumee.api.common;
 
import com.alibaba.fastjson.JSONObject;
import com.doumee.api.BaseController;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.annotation.trace.Trace;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.aliyun.ALiYunUtil;
import com.doumee.core.wx.WxMiniConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
 
/**
 * @author Eva.Caesar Liu
 * @date 2023/02/14 11:14
 */
@Api(tags = "公共接口")
@Trace(exclude = true)
@RestController
@RequestMapping("/public")
@Slf4j
public class PublicController extends BaseController {
 
 
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
 
 
    @ApiOperation(value = "上传", notes = "上传", httpMethod = "POST", position = 6)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "folder", value = "文件夹", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public void uploadMobile(String folder, HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        upload(multipartRequest, response, folder + "/",
            systemDictDataBiz.queryByCode(Constants.OSS,Constants.BUCKETNAME).getCode(),
            systemDictDataBiz.queryByCode(Constants.OSS,Constants.ACCESS_ID).getCode(),
            systemDictDataBiz.queryByCode(Constants.OSS,Constants.ACCESS_KEY).getCode(),
            systemDictDataBiz.queryByCode(Constants.OSS,Constants.RESOURCE_PATH).getCode(),
            systemDictDataBiz.queryByCode(Constants.OSS,Constants.ENDPOINT).getCode());
    }
 
 
    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST", position = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "folder", value = "文件夹", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping(value = "/uploadPicture", headers = "content-type=multipart/form-data")
    public void uploadPicture(String folder, HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartRequest.getFileNames();
        Map<String, Object> context = new HashMap<>();
        while (fileNames.hasNext()){
            MultipartFile file = multipartRequest.getFile(fileNames.next());
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            if ( !StringUtils.equalsIgnoreCase(suffix, ".jpg") || !StringUtils.equalsIgnoreCase(suffix, ".png")) {
                context.put("code", 0);
                context.put("message", "对不起,文件格式上传有误!");
            }
        }
        upload(multipartRequest, response, folder + "/",
                systemDictDataBiz.queryByCode(Constants.OSS,Constants.BUCKETNAME).getCode(),
                systemDictDataBiz.queryByCode(Constants.OSS,Constants.ACCESS_ID).getCode(),
                systemDictDataBiz.queryByCode(Constants.OSS,Constants.ACCESS_KEY).getCode(),
                systemDictDataBiz.queryByCode(Constants.OSS,Constants.RESOURCE_PATH).getCode(),
                systemDictDataBiz.queryByCode(Constants.OSS,Constants.ENDPOINT).getCode());
    }
 
    public void upload(HttpServletRequest request, HttpServletResponse response, String folder, String bucketName,
        String access_id, String access_key, String resourcePath, String endpoint) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Map<String, Object> context = new HashMap<>();
        CommonsMultipartResolver multipartResovler = new CommonsMultipartResolver();
        if (multipartResovler.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> it = multipartRequest.getFileNames();
            while (it.hasNext()) {
                MultipartFile file = multipartRequest.getFile((String) it.next());
                if (file != null) {
                    String uploadFileName = file.getOriginalFilename();
                    String originname = uploadFileName;
                    if (originname.lastIndexOf("/") >= 0) {
                        originname = originname.substring(originname.lastIndexOf("/") + 1);
                    }
                    String nfix = "";
                    if (StringUtils.isNotBlank(uploadFileName)) {
                        nfix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
                    }
                    if (StringUtils.equalsIgnoreCase(nfix, ".exe")) {
                        context.put("code", 4000);
                        context.put("message", "对不起,文件格式\".exe\"上传有误!");
                        return;
                    }
                    if (StringUtils.equalsIgnoreCase(nfix, ".dll")) {
                        context.put("code", 4000);
                        context.put("message", "对不起,文件格式\".dll\"上传有误!");
                        return;
                    }
 
                    if (isImageFile(nfix)) {
                        File tempFile = null;
                        try {
                            tempFile = File.createTempFile("wx_check_", nfix);
                            java.io.FileOutputStream fos = new java.io.FileOutputStream(tempFile);
                            fos.write(file.getBytes());
                            fos.close();
                            boolean isSafe = WxMiniConfig.wxMaService.getSecurityService().checkImage(tempFile);
                            if (!isSafe) {
                                context.put("code", 4001);
                                context.put("message", "图片内容不合规,请更换图片后重试");
                                writerJson(response, context);
                                return;
                            }
                        } catch (WxErrorException e) {
                            log.warn("微信图片安全检测失败: {}", e.getMessage());
                        } finally {
                            if (tempFile != null && tempFile.exists()) {
                                tempFile.delete();
                            }
                        }
                    }
 
                    String nowDate = DateUtil.getNowShortDate();
                    String fileName = UUID.randomUUID().toString() + nfix;
                    String tempFileName = nowDate + "/" + fileName;
                    String key = folder + tempFileName;
                    ALiYunUtil obs = new ALiYunUtil(endpoint,access_id, access_key);
                    if (obs.uploadOnlineObject(file.getInputStream(),bucketName, key,null)) {
                        context.put("success", true);
                        context.put("code", 200);
                        context.put("errno",0);
                        JSONObject fileJSON = new JSONObject();
                        fileJSON.put("url", resourcePath + key);
                        fileJSON.put("imgaddr", tempFileName);
                        fileJSON.put("imgname", fileName);
                        fileJSON.put("originname", originname);
                        context.put("data",fileJSON);
                        context.put("message","请求成功");
                        writerJson(response, context);
                        return;
                    } else {
                        context.put("code", 0);
                        context.put("message", "上传失败");
                        writerJson(response, context);
                        return;
                    }
                }
 
            }
        }
        context.put("code", 0);
        context.put("message", "上传失败");
        context.put("errno",0);
        writerJson(response, context);
        return;
    }
 
    private boolean isImageFile(String suffix) {
        if (StringUtils.isBlank(suffix)) {
            return false;
        }
        String lowerSuffix = suffix.toLowerCase();
        return lowerSuffix.equals(".jpg") || lowerSuffix.equals(".jpeg") 
            || lowerSuffix.equals(".png") || lowerSuffix.equals(".gif") 
            || lowerSuffix.equals(".bmp") || lowerSuffix.equals(".webp");
    }
 
    public static void writerJson(HttpServletResponse response, Object object) {
        response.setContentType("application/json");
        writer(response, JSONObject.toJSONString(object));
    }
 
    private static void writer(HttpServletResponse response, String str) {
        try {
            StringBuffer result = new StringBuffer();
            //设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}