FileUploadController.java 16.7 KB
Newer Older
liqin's avatar
liqin committed
1 2
package cn.wisenergy.chnmuseum.party.web.controller;

liqin's avatar
liqin committed
3
import cn.hutool.core.util.ArrayUtil;
liqin's avatar
liqin committed
4 5 6 7 8 9 10
import cn.wisenergy.chnmuseum.party.common.dfs.FastDFSUtils;
import cn.wisenergy.chnmuseum.party.common.enums.FileTypeEnum;
import cn.wisenergy.chnmuseum.party.common.enums.HANDLE_STATUS_ENUM;
import cn.wisenergy.chnmuseum.party.common.enums.RESPONSE_CODE_ENUM;
import cn.wisenergy.chnmuseum.party.common.mvc.InterfaceException;
import cn.wisenergy.chnmuseum.party.common.vo.BatchUploadResVO;
import cn.wisenergy.chnmuseum.party.common.vo.ImageUploadResult;
liqin's avatar
liqin committed
11
import io.swagger.annotations.Api;
liqin's avatar
liqin committed
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
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 文件上传 前端控制器
 * </p>
 *
 * @author Danny Lee
 * @since 2021-03-16
 */
@Slf4j
@RestController
@RequestMapping("/file")
liqin's avatar
liqin committed
42
@Api(tags = {"文件上传接口"})
liqin's avatar
liqin committed
43 44 45
public class FileUploadController {

    private static final String[] IMAGE_TYPE = new String[]{"JPG", "JPEG", "PNG", "BMP", "WBMP"};
liqin's avatar
liqin committed
46
    private static final String[] AUDIO_TYPE = new String[]{"MP3", "AAC", "WMA", "WAV", "FLAC", "RM", "OGG"};
liqin's avatar
liqin committed
47
    private static final String[] VIDEO_TYPE = new String[]{"MP4", "FLV"};
liqin's avatar
liqin committed
48 49
    private static final String[] DOC_TYPE = new String[]{"PDF", "DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX"};
    private static final String[] DATUM_TYPE = ArrayUtil.addAll(DOC_TYPE, IMAGE_TYPE, VIDEO_TYPE);
liqin's avatar
liqin committed
50

liqin's avatar
liqin committed
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
//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    public ResponseEntity<PicUploadResult> upload(@RequestParam(value = "bc_cover", required = true) MultipartFile uploadFile, HttpServletResponse response) throws Exception {
//        // 校验文件扩展名
//        boolean isLegal = false;
//        for (String type : IMAGE_TYPE) {
//            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
//                isLegal = true;
//                break;
//            }
//        }
//        byte[] bytes = uploadFile.getBytes();
//        if (ImageUtil.isPicture(uploadFile.getOriginalFilename()) && ImageUtil.isImage(bytes) && ImageUtil.isImage1(bytes)) {
//            isLegal = true;
//        } else {
//            isLegal = false;
//            throw new RuntimeException("图片文件不合法");
//        }
//
//        // 封装Result对象,并且将文件的byte数组放置到result对象中
//        PicUploadResult fileUploadResult = new PicUploadResult();
//        // 状态
//        fileUploadResult.setError(isLegal ? 0 : 1);
//        // 文件新路径
//        String filePath = FastDFSUtils.uploadPic(bytes, uploadFile.getOriginalFilename(), uploadFile.getSize());
//
//        if (log.isDebugEnabled()) {
//            log.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
//        }
//        String picUrl = IMAGE_BASE_URL + filePath;
//        fileUploadResult.setUrl(picUrl);
//        isLegal = false;
//        try {
//            BufferedImage image = ImageIO.read(new URL(picUrl));
//            if (image != null) {
//                // fileUploadResult.setWidth(image.getWidth() + "");
//                // fileUploadResult.setHeight(image.getHeight() + "");
//                isLegal = true;
//            }
//        } catch (IOException e) {
//            log.error("check image is legal error! " + e.getMessage());
//        }
//        isLegal = true;
//        fileUploadResult.setError(isLegal ? 0 : 1);
//        if (!isLegal) {
//            // 不合法,将磁盘上的文件删除
//            FastDFSUtils.deletePic(picUrl);
//        }
//        return ResponseEntity.status(HttpStatus.CREATED).body(fileUploadResult);
//    }

liqin's avatar
liqin committed
101
    @ApiImplicitParams({
liqin's avatar
liqin committed
102
            @ApiImplicitParam(name = "file", value = "资料", paramType = "form", dataType = "__file", collectionFormat = "array", allowMultiple = true)
liqin's avatar
liqin committed
103
    })
liqin's avatar
liqin committed
104
    @PostMapping(value = "/datum/upload", headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
liqin's avatar
liqin committed
105
    @ApiOperation(value = "资料上传", notes = "资料上传")
liqin's avatar
liqin committed
106
    public ResponseEntity<BatchUploadResVO> uploadFile(@RequestPart(value = "file", required = false) MultipartFile[] files) throws IOException {
liqin's avatar
liqin committed
107
        if (files.length == 0) {
wzp's avatar
wzp committed
108
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "没有文件可供上传");
liqin's avatar
liqin committed
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
        }
        int successCount = 0;
        int failureCount = 0;
        List<BatchUploadResVO.HandleResult> handleList = new ArrayList<>();

        List<String> videoUrlList = new ArrayList<>();
        for (MultipartFile file : files) {
            // 当前维度表下线结果
            BatchUploadResVO.HandleResult handleResult = new BatchUploadResVO.HandleResult();
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                handleResult.setFileName("");
                handleResult.setFileType(FileTypeEnum.DATUM.getName());
                handleResult.setFileUrl("");
                handleResult.setHandleResult(HANDLE_STATUS_ENUM.FAILURE.getName());
                handleResult.setDescription("文件名为空");
                failureCount++;
                continue;
            }

            handleResult.setFileName(originalFilename);
            handleResult.setFileType(FileTypeEnum.DATUM.getName());
            handleResult.setHandleResult(HANDLE_STATUS_ENUM.SUCCESS.getName());
            boolean anyMatch = Arrays.stream(DATUM_TYPE).anyMatch(s -> Objects.equals(s, FilenameUtils.getExtension(originalFilename).toUpperCase()));
            if (anyMatch) {
                String url = FastDFSUtils.uploadFile(file.getInputStream(), file.getSize(), originalFilename);
                handleResult.setFileUrl(url);
                handleResult.setDescription("操作成功");
                videoUrlList.add(url);
                successCount++;
            } else {
                handleResult.setFileUrl("");
                handleResult.setDescription("文件格式不支持");
                failureCount++;
            }
            // 设置处理的业务表信息
            handleList.add(handleResult);
        }

        BatchUploadResVO batchUploadResVO = new BatchUploadResVO();
        batchUploadResVO.setFailureCount(failureCount);
        batchUploadResVO.setSuccessCount(successCount);
        batchUploadResVO.setTotal(files.length);
        batchUploadResVO.setHandleList(handleList);
        batchUploadResVO.setUrlList(videoUrlList);
wzp's avatar
wzp committed
155
        return ResponseEntity.ok(batchUploadResVO);
liqin's avatar
liqin committed
156 157 158 159
    }

    @PostMapping(value = "/image/upload", headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RequiresPermissions("image:upload")
liqin's avatar
liqin committed
160
    @ApiOperation(value = "单图片上传", notes = "单图片上传")
liqin's avatar
liqin committed
161
    public ResponseEntity<ImageUploadResult> uploadImage(@RequestParam(value = "file") MultipartFile uploadFile) throws Exception {
liqin's avatar
liqin committed
162
        if (uploadFile == null || uploadFile.getSize() == 0) {
wzp's avatar
wzp committed
163
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "没有文件可供上传");
liqin's avatar
liqin committed
164 165 166 167
        }
        String fileName = uploadFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        if (StringUtils.isBlank(extension)) {
wzp's avatar
wzp committed
168
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "文件格式不支持");
liqin's avatar
liqin committed
169 170 171
        }
        boolean anyMatch = Arrays.stream(IMAGE_TYPE).anyMatch(s -> Objects.equals(s, extension.toUpperCase()));
        if (!anyMatch) {
wzp's avatar
wzp committed
172
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "文件格式不支持");
liqin's avatar
liqin committed
173 174 175 176 177 178 179 180
        }

        String url = FastDFSUtils.uploadFile(uploadFile.getInputStream(), uploadFile.getSize(), fileName);
        ImageUploadResult imageUploadResult = new ImageUploadResult();
        imageUploadResult.setFileName(fileName);
        imageUploadResult.setFileExtName(extension);
        imageUploadResult.setFileSize(uploadFile.getSize());
        imageUploadResult.setUrl(url);
wzp's avatar
wzp committed
181
        return ResponseEntity.ok(imageUploadResult);
liqin's avatar
liqin committed
182 183
    }

184

185
    @PostMapping(value = "/upload/allType", headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
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
    @RequiresPermissions("file:upload:allType")
    @ApiOperation(value = "单文件上传(不限格式)", notes = "单文件上传(不限格式)")
    public ResponseEntity<ImageUploadResult> uploadAllType(@RequestParam(value = "file") MultipartFile uploadFile) throws Exception {
        if (uploadFile == null || uploadFile.getSize() == 0) {
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "没有文件可供上传");
        }
        String fileName = uploadFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        if (StringUtils.isBlank(extension)) {
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "文件格式不支持");
        }
//        boolean anyMatch = Arrays.stream(IMAGE_TYPE).anyMatch(s -> Objects.equals(s, extension.toUpperCase()));
//        if (!anyMatch) {
//            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "文件格式不支持");
//        }

        String url = FastDFSUtils.uploadFile(uploadFile.getInputStream(), uploadFile.getSize(), fileName);
        ImageUploadResult imageUploadResult = new ImageUploadResult();
        imageUploadResult.setFileName(fileName);
        imageUploadResult.setFileExtName(extension);
        imageUploadResult.setFileSize(uploadFile.getSize());
        imageUploadResult.setUrl(url);
        return ResponseEntity.ok(imageUploadResult);
    }

liqin's avatar
liqin committed
211 212 213 214 215 216 217
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "音频文件", paramType = "form", dataType = "__file", collectionFormat = "array", allowMultiple = true)
    })
    @PostMapping(value = "/audio/upload", headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RequiresPermissions("audio:upload")
    @ApiOperation(value = "多音频上传", notes = "多音频上传")
    public ResponseEntity<BatchUploadResVO> uploadAudio(@RequestPart(value = "file", required = false) MultipartFile[] files) throws IOException {
wzp's avatar
wzp committed
218 219
        if (files == null || files.length == 0) {
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "没有文件可供上传");
liqin's avatar
liqin committed
220 221 222
        }
        final boolean existChineseAudio = Arrays.stream(files).anyMatch(s -> Objects.requireNonNull(s.getOriginalFilename()).contains("汉语"));
        if (!existChineseAudio) {
wzp's avatar
wzp committed
223
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "必须包含汉语音频");
liqin's avatar
liqin committed
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
        }

        int successCount = 0;
        int failureCount = 0;
        List<BatchUploadResVO.HandleResult> handleList = new ArrayList<>();

        List<String> videoUrlList = new ArrayList<>();
        for (MultipartFile file : files) {
            // 当前维度表下线结果
            BatchUploadResVO.HandleResult handleResult = new BatchUploadResVO.HandleResult();
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                handleResult.setFileName("");
                handleResult.setFileType(FileTypeEnum.AUDIO.getName());
                handleResult.setFileUrl("");
                handleResult.setHandleResult(HANDLE_STATUS_ENUM.FAILURE.getName());
                handleResult.setDescription("文件名为空");
                failureCount++;
                continue;
            }

            handleResult.setFileName(originalFilename);
            handleResult.setFileType(FileTypeEnum.AUDIO.getName());
            handleResult.setHandleResult(HANDLE_STATUS_ENUM.SUCCESS.getName());
            boolean anyMatch = Arrays.stream(AUDIO_TYPE).anyMatch(s -> Objects.equals(s, FilenameUtils.getExtension(originalFilename).toUpperCase()));
            if (anyMatch) {
                String url = FastDFSUtils.uploadFile(file.getInputStream(), file.getSize(), originalFilename);
                handleResult.setFileUrl(url);
                handleResult.setDescription("操作成功");
                videoUrlList.add(url);
                successCount++;
            } else {
                handleResult.setFileUrl("");
                handleResult.setDescription("文件格式不支持");
                failureCount++;
            }
            // 设置处理的业务表信息
            handleList.add(handleResult);
        }

        BatchUploadResVO batchUploadResVO = new BatchUploadResVO();
        batchUploadResVO.setFailureCount(failureCount);
        batchUploadResVO.setSuccessCount(successCount);
        batchUploadResVO.setTotal(files.length);
        batchUploadResVO.setHandleList(handleList);
        batchUploadResVO.setUrlList(videoUrlList);
wzp's avatar
wzp committed
271
        return ResponseEntity.ok(batchUploadResVO);
liqin's avatar
liqin committed
272 273
    }

liqin's avatar
liqin committed
274
    @ApiImplicitParams({
liqin's avatar
liqin committed
275
            @ApiImplicitParam(name = "file", value = "视频文件", paramType = "form", dataType = "__file", collectionFormat = "array", allowMultiple = true)
liqin's avatar
liqin committed
276 277 278 279
    })
    @PostMapping(value = "/video/upload", headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RequiresPermissions("video:upload")
    @ApiOperation(value = "多视频上传", notes = "多视频上传")
wzp's avatar
wzp committed
280
    public ResponseEntity<BatchUploadResVO> uploadVideo(@RequestPart(value = "file", required = true) MultipartFile[] files) throws IOException {
liqin's avatar
liqin committed
281
        if (files == null || files.length == 0) {
wzp's avatar
wzp committed
282
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "没有文件可供上传");
liqin's avatar
liqin committed
283
        }
liqin's avatar
liqin committed
284
        final boolean matchChinese = Arrays.stream(files).anyMatch(s -> Objects.requireNonNull(s.getOriginalFilename()).contains("汉语"));
liqin's avatar
liqin committed
285
        if (!matchChinese) {
wzp's avatar
wzp committed
286
            throw new InterfaceException(RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode(), "必须包含汉语视频");
liqin's avatar
liqin committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        }

        int successCount = 0;
        int failureCount = 0;
        List<BatchUploadResVO.HandleResult> handleList = new ArrayList<>();

        List<String> videoUrlList = new ArrayList<>();
        for (MultipartFile file : files) {
            // 当前维度表下线结果
            BatchUploadResVO.HandleResult handleResult = new BatchUploadResVO.HandleResult();
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                handleResult.setFileName("");
                handleResult.setFileType(FileTypeEnum.VIDEO.getName());
                handleResult.setFileUrl("");
                handleResult.setHandleResult(HANDLE_STATUS_ENUM.FAILURE.getName());
                handleResult.setDescription("文件名为空");
                failureCount++;
                continue;
            }

            handleResult.setFileName(originalFilename);
            handleResult.setFileType(FileTypeEnum.VIDEO.getName());
liqin's avatar
liqin committed
311
            handleResult.setHandleResult(HANDLE_STATUS_ENUM.SUCCESS.getName());
liqin's avatar
liqin committed
312 313
            boolean anyMatch = Arrays.stream(VIDEO_TYPE).anyMatch(s -> Objects.equals(s, FilenameUtils.getExtension(originalFilename).toUpperCase()));
            if (anyMatch) {
liqin's avatar
liqin committed
314
                String url = FastDFSUtils.uploadVideo(file.getInputStream(), file.getSize(), originalFilename);
liqin's avatar
liqin committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                handleResult.setFileUrl(url);
                handleResult.setDescription("操作成功");
                videoUrlList.add(url);
                successCount++;
            } else {
                handleResult.setFileUrl("");
                handleResult.setDescription("文件格式不支持");
                failureCount++;
            }
            // 设置处理的业务表信息
            handleList.add(handleResult);
        }

        BatchUploadResVO batchUploadResVO = new BatchUploadResVO();
        batchUploadResVO.setFailureCount(failureCount);
        batchUploadResVO.setSuccessCount(successCount);
        batchUploadResVO.setTotal(files.length);
        batchUploadResVO.setHandleList(handleList);
        batchUploadResVO.setUrlList(videoUrlList);
wzp's avatar
wzp committed
334
        return ResponseEntity.ok(batchUploadResVO);
liqin's avatar
liqin committed
335 336 337
    }

}