Bladeren bron

文件上传接口拆分为管理端和用户端接口,并限制只能上传图片

codingliang 8 maanden geleden
bovenliggende
commit
277817682a

+ 0 - 1
src/main/java/com/sqx/modules/app/service/impl/UserServiceImpl.java

@@ -51,7 +51,6 @@ import com.sqx.modules.app.utils.UserConstantInterface;
 import com.sqx.modules.common.entity.CommonInfo;
 import com.sqx.modules.common.service.CommonInfoService;
 import com.sqx.modules.errand.entity.Feedback;
-import com.sqx.modules.file.utils.Md5Utils;
 import com.sqx.modules.integral.dao.UserIntegralDao;
 import com.sqx.modules.integral.entity.UserIntegral;
 import com.sqx.modules.message.entity.MessageInfo;

+ 6 - 330
src/main/java/com/sqx/modules/file/AliFileUploadController.java

@@ -1,46 +1,17 @@
 package com.sqx.modules.file;
 
-import cn.hutool.core.util.StrUtil;
-import com.aliyun.oss.OSS;
-import com.aliyun.oss.OSSClientBuilder;
-import com.sqx.common.exception.SqxException;
 import com.sqx.common.utils.Result;
-import com.sqx.config.MinioConfig;
-import com.sqx.modules.common.service.CommonInfoService;
-import com.sqx.modules.file.utils.FileUploadUtils;
+import com.sqx.modules.file.service.NewFileService;
 import icu.xuyijie.secureapi.annotation.DecryptParam;
-import io.minio.MinioClient;
-import io.minio.ObjectWriteResponse;
-import io.minio.PutObjectArgs;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.fileupload.disk.DiskFileItem;
-import org.apache.commons.lang.StringUtils;
-import org.apache.poi.util.IOUtils;
-import org.jaudiotagger.audio.AudioFileIO;
-import org.jaudiotagger.audio.mp3.MP3AudioHeader;
-import org.jaudiotagger.audio.mp3.MP3File;
-import org.springframework.boot.system.ApplicationHome;
-import org.springframework.util.ClassUtils;
-import org.springframework.util.StreamUtils;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.multipart.commons.CommonsMultipartFile;
-
-import java.io.*;
-import java.net.URLDecoder;
-import java.nio.file.Files;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.UUID;
 
 /**
  * 阿里云文件上传
@@ -48,314 +19,19 @@ import java.util.UUID;
  * @date 2020/7/13
  */
 @Slf4j
-@Api(value = "阿里云文件上传", tags = {"阿里云文件上传"})
+@Api(value = "阿里云文件上传(即将删除)", tags = {"阿里云文件上传"})
 @RestController
 @RequestMapping(value = "/alioss")
 @RequiredArgsConstructor
 public class AliFileUploadController {
 
-    private final CommonInfoService commonRepository;
-    private final MinioClient minioClient;
-    private final MinioConfig minioConfig;
+    private final NewFileService newFileService;
 
     @RequestMapping(value = "/upload", method = RequestMethod.POST)
     @ApiOperation("文件上传")
     @ResponseBody
     public Result upload(@DecryptParam("file") MultipartFile file){
-        String value = commonRepository.findOne(234).getValue();
-        if("1".equals(value)){
-            // 创建OSSClient实例。
-            OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
-            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
-            // 上传文件流。
-            InputStream inputStream = null;
-            try {
-                inputStream =new ByteArrayInputStream(file.getBytes());
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-            String completePath=getPath(suffix);
-            ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
-            // 关闭OSSClient。
-            ossClient.shutdown();
-            String src = commonRepository.findOne(72).getValue()+"/"+completePath;
-            // String src = commonRepository.findOne(19).getValue()+"/img/"+completePath;
-            return Result.success().put("data",src);
-        } else if (StrUtil.equals(value, "3")) {
-            // Minio上传
-            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
-            String completePath = getPath(suffix);
-//            long fileSize =file.getSize();
-            try {
-                //图片压缩webp
-//                InputStream inputStream=file.getInputStream();
-//                if(this.isPicture(suffix)&&file.getSize()>1024*1024*2){
-//                    completePath=getPath(".webp");
-//                    String tmpPath =UUID.randomUUID().toString().replaceAll("-", "")+".webp";
-//                    ApplicationHome applicationHome = new ApplicationHome(AliFileUploadController.class);
-//                    String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
-//                    String decode = URLDecoder.decode(pathResouce, "utf-8");
-//                    File newFile = new File(decode + tmpPath);
-//                    ImageOutputStream  ios=null;
-//                    try {
-//                        BufferedImage image = ImageIO.read(inputStream);
-//                        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
-//                        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
-//                        writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
-//                        // 设置有损压缩
-//                        writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSY_COMPRESSION]);
-//                        //设置 80% 的质量. 设置范围 0-1
-//                        writeParam.setCompressionQuality(0.8f);
-//                        // Save the image
-//                        ios =ImageIO.createImageOutputStream(newFile);
-//                        writer.setOutput(ios);
-//                        writer.write(null, new IIOImage(image, null, null), writeParam);
-//                        writer.dispose();
-//                        ios.close();
-//                        minioClient.putObject(PutObjectArgs.builder()
-//                                .bucket(minioConfig.getBucket())
-//                                .object(completePath)
-//                                .stream(Files.newInputStream(newFile.toPath()), newFile.length(), -1)
-//                                .build());
-//                        inputStream.close();
-//                        delteTempFile(newFile);
-//                        String src = commonRepository.findOne(72).getValue() + "/" + completePath;
-//                        return Result.success().put("data", src);
-//                    } catch (IOException e) {
-//                        throw new RuntimeException(e);
-//                    }finally {
-//                        try {
-//                            if(inputStream!=null){
-//                                inputStream.close();
-//                            }
-//                            if(ios!=null){
-//                                ios.close();
-//                            }
-//                        } catch (IOException e) {
-//                            log.info(e.getMessage());
-//                        }
-//                    }
-//                }
-                minioClient.putObject(PutObjectArgs.builder()
-                        .bucket(minioConfig.getBucket())
-                        .object(completePath)
-                        .stream(file.getInputStream(), file.getSize(), -1)
-                        .build());
-
-                String src = commonRepository.findOne(72).getValue() + "/" + completePath;
-                return Result.success().put("data", src);
-            } catch (Exception e) {
-                throw new SqxException("文件上传失败!");
-            }
-        } else{
-            try
-            {
-                String http = commonRepository.findOne(19).getValue();
-                String[] split = http.split("://");
-                // 上传文件路径
-                String filePath ="/mydata/project/media/"+split[1]+"/file/uploadPath";
-                // 上传并返回新文件名称
-                String fileName = FileUploadUtils.upload(filePath, file);
-                String url = http +fileName;
-                return Result.success().put("data",url);
-            }
-            catch (Exception e)
-            {
-                log.error("本地上传失败:"+e.getMessage(),e);
-                return Result.error(-100,"文件上传失败!");
-            }
-        }
-
-    }
-
-    @RequestMapping(value = "/uploadUniApp", method = RequestMethod.POST)
-    @ApiOperation("文件上传")
-    @ResponseBody
-    public String uploadUniApp(@DecryptParam("file") MultipartFile file){
-        String value = commonRepository.findOne(234).getValue();
-        if("1".equals(value)){
-            // 创建OSSClient实例。
-            OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
-            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
-            // 上传文件流。
-            InputStream inputStream = null;
-            try {
-                inputStream =new ByteArrayInputStream(file.getBytes());
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-            String completePath=getPath(suffix);
-            ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
-            // 关闭OSSClient。
-            ossClient.shutdown();
-
-            String src = commonRepository.findOne(72).getValue()+"/"+completePath;
-            // String src = commonRepository.findOne(19).getValue()+"/img/"+completePath;
-
-            return src;
-        }else{
-            try
-            {
-                String http = commonRepository.findOne(19).getValue();
-                String[] split = http.split("://");
-                // 上传文件路径
-                String filePath ="/mydata/project/media/"+split[1]+"/file/uploadPath";
-                // 上传并返回新文件名称
-                String fileName = FileUploadUtils.upload(filePath, file);
-                String url = http +fileName;
-                return url;
-            }
-            catch (Exception e)
-            {
-                log.error("本地上传失败:"+e.getMessage(),e);
-                return null;
-            }
-        }
-
-    }
-
-    @RequestMapping(value = "/uploadMusic", method = RequestMethod.POST)
-    @ApiOperation("文件上传")
-    @ResponseBody
-    public Result uploadMusic(@DecryptParam("file") MultipartFile file) {
-        String url="";
-        String value = commonRepository.findOne(234).getValue();
-        if("1".equals(value)){
-            // 创建OSSClient实例。
-            OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
-            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
-            // 上传文件流。
-            InputStream inputStream = null;
-            try {
-                inputStream =new ByteArrayInputStream(file.getBytes());
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-            String completePath=getPath(suffix);
-            ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
-            // 关闭OSSClient。
-            ossClient.shutdown();
-
-            url = commonRepository.findOne(72).getValue()+"/"+completePath;
-            // url = commonRepository.findOne(19).getValue()+"/img/"+completePath;
-        }else{
-            try
-            {
-                String http = commonRepository.findOne(19).getValue();
-                String[] split = http.split("://");
-                // 上传文件路径
-                String filePath ="/mydata/project/media/"+split[1]+"/file/uploadPath";
-                // 上传并返回新文件名称
-                String fileName = FileUploadUtils.upload(filePath, file);
-                url = http +fileName;
-            }
-            catch (Exception e)
-            {
-                log.error("本地上传失败:"+e.getMessage(),e);
-                return null;
-            }
-        }
-        if("/".equals(url.substring(url.length()-1,url.length()))){
-            url=url.substring(0,url.length()-1);
-        }
-        int trackLength=0;
-        try {
-            File file1 = multipartFileToFile(file);
-            MP3File f = (MP3File) AudioFileIO.read(file1);
-            MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
-            trackLength = audioHeader.getTrackLength();
-            delteTempFile(file1);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        Map<String,Object> result=new HashMap<>();
-        result.put("url",url);
-        result.put("sec",trackLength);
-        return Result.success().put("data",result );
+        String src = newFileService.upload(file);
+        return Result.success().put("data",src);
     }
-
-
-    /**
-     * MultipartFile 转 File
-     *
-     * @param file
-     * @throws Exception
-     */
-    public static File multipartFileToFile(MultipartFile file) throws Exception {
-
-        File toFile = null;
-        if (file.equals("") || file.getSize() <= 0) {
-            file = null;
-        } else {
-            InputStream ins = null;
-            ins = file.getInputStream();
-            toFile = new File(file.getOriginalFilename());
-            inputStreamToFile(ins, toFile);
-            ins.close();
-        }
-        return toFile;
-    }
-
-    //获取流文件
-    private static void inputStreamToFile(InputStream ins, File file) {
-        try {
-            OutputStream os = new FileOutputStream(file);
-            int bytesRead = 0;
-            byte[] buffer = new byte[8192];
-            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
-                os.write(buffer, 0, bytesRead);
-            }
-            os.close();
-            ins.close();
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * 删除本地临时文件
-     * @param file
-     */
-    public static void delteTempFile(File file) {
-        if (file != null) {
-            File del = new File(file.toURI());
-            del.delete();
-        }
-    }
-
-    private String getPath(String suffix) {
-        //生成uuid
-        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
-        //文件路径
-        String path =format(new Date()) + "/" + uuid;
-        return path + suffix;
-    }
-
-
-    private String format(Date date) {
-        if(date != null){
-            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
-            return df.format(date);
-        }
-        return null;
-    }
-    /**
-     * 判断文件是否为图片
-     */
-    public boolean isPicture(String imgName) {
-        boolean flag = false;
-        if (StringUtils.isBlank(imgName)) {
-            return false;
-        }
-        String[] arr = {".bmp", ".dib", ".gif", ".jfif", ".jpe", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".ico"};
-        for (String item : arr) {
-            if (item.equals(imgName)) {
-                flag = true;
-                break;
-            }
-        }
-        return flag;
-    }
-
-
-}
+}

+ 32 - 0
src/main/java/com/sqx/modules/file/NewFileController.java

@@ -0,0 +1,32 @@
+package com.sqx.modules.file;
+
+import com.sqx.common.utils.Result;
+import com.sqx.modules.file.service.NewFileService;
+import icu.xuyijie.secureapi.annotation.DecryptParam;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * @author codingliang
+ * @date 2025-10-21
+ */
+@Api(value = "文件上传(管理员端)")
+@RestController
+@RequestMapping(value = "admin/new-file")
+@RequiredArgsConstructor
+public class NewFileController {
+
+    private final NewFileService newFileService;
+
+    @ApiOperation("文件上传")
+    @RequestMapping(value = "upload", method = RequestMethod.POST)
+    public Result upload(@DecryptParam("file") MultipartFile file){
+        String src = newFileService.upload(file);
+        return Result.success().put("data",src);
+    }
+}

+ 34 - 0
src/main/java/com/sqx/modules/file/app/AppNewFileController.java

@@ -0,0 +1,34 @@
+package com.sqx.modules.file.app;
+
+import com.sqx.common.utils.Result;
+import com.sqx.modules.app.annotation.Login;
+import com.sqx.modules.file.service.NewFileService;
+import icu.xuyijie.secureapi.annotation.DecryptParam;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * @author codingliang
+ * @date 2025-10-21
+ */
+@Api(value = "文件上传(用户端)")
+@RestController
+@RequestMapping(value = "app/new-file")
+@RequiredArgsConstructor
+public class AppNewFileController {
+
+    private final NewFileService newFileService;
+
+    @Login
+    @ApiOperation("文件上传")
+    @RequestMapping(value = "upload", method = RequestMethod.POST)
+    public Result upload(@DecryptParam("file") MultipartFile file){
+        String src = newFileService.upload(file);
+        return Result.success().put("data",src);
+    }
+}

+ 97 - 0
src/main/java/com/sqx/modules/file/service/NewFileService.java

@@ -0,0 +1,97 @@
+package com.sqx.modules.file.service;
+
+import cn.hutool.core.util.StrUtil;
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.sqx.common.exception.SqxException;
+import com.sqx.config.MinioConfig;
+import com.sqx.modules.common.service.CommonInfoService;
+import com.sqx.modules.file.utils.FileUploadUtils;
+import com.sqx.modules.file.utils.MimeTypeUtils;
+import io.minio.MinioClient;
+import io.minio.PutObjectArgs;
+import lombok.RequiredArgsConstructor;
+import org.apache.commons.lang3.time.DateFormatUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Date;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * @author codingliang
+ * @date 2025-10-21
+ */
+@Service
+@RequiredArgsConstructor
+public class NewFileService {
+
+    private final CommonInfoService commonInfoService;
+    private final MinioClient minioClient;
+    private final MinioConfig minioConfig;
+
+    public String upload(MultipartFile file) {
+        // 新增图片类型验证
+        String extension = FileUploadUtils.getExtension(file);
+        if (!FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
+            throw new SqxException("文件必须为图片类型");
+        }
+
+        // 上传方式 1阿里云oss  2本地 3 minio
+        String value = commonInfoService.findOne(234).getValue();
+        if(StrUtil.equals(value, "1")){
+            // 创建OSSClient实例。
+            OSS ossClient = new OSSClientBuilder().build(commonInfoService.findOne(68).getValue(), commonInfoService.findOne(69).getValue(), commonInfoService.findOne(70).getValue());
+            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
+            // 上传文件流
+            InputStream inputStream;
+            try {
+                inputStream = new ByteArrayInputStream(file.getBytes());
+            } catch (IOException e) {
+                throw new SqxException("文件上传失败!" + e.getMessage());
+            }
+            String completePath = getPath(suffix);
+            ossClient.putObject(commonInfoService.findOne(71).getValue(), completePath, inputStream);
+            ossClient.shutdown();
+            return commonInfoService.findOne(72).getValue()+ "/" + completePath;
+        } else if (StrUtil.equals(value, "3")) {
+            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
+            String completePath = getPath(suffix);
+            try {
+                minioClient.putObject(PutObjectArgs.builder()
+                        .bucket(minioConfig.getBucket())
+                        .object(completePath)
+                        .stream(file.getInputStream(), file.getSize(), -1)
+                        .build());
+
+                return commonInfoService.findOne(72).getValue() + "/" + completePath;
+            } catch (Exception e) {
+                throw new SqxException("文件上传失败!");
+            }
+        } else{
+            try {
+                String http = commonInfoService.findOne(19).getValue();
+                String[] split = http.split("://");
+                // 上传文件路径
+                String filePath ="/mydata/project/media/" + split[1] + "/file/uploadPath";
+                // 上传并返回新文件名称
+                String fileName = FileUploadUtils.upload(filePath, file);
+                return http + fileName;
+            } catch (Exception e) {
+                throw new SqxException("文件上传失败!");
+            }
+        }
+    }
+
+    private String getPath(String suffix) {
+        // 生成uuid
+        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
+        // 文件路径
+        String path = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/" + uuid;
+        return path + suffix;
+    }
+}

+ 0 - 34
src/main/java/com/sqx/modules/file/utils/DescribeException.java

@@ -1,34 +0,0 @@
-package com.sqx.modules.file.utils;
-
-public class DescribeException extends RuntimeException{
-
-    private Integer code;
-
-    /**
-     * 继承exception,加入错误状态值
-     * @param exceptionEnum
-     */
-    public DescribeException(ExceptionEnum exceptionEnum) {
-        super(exceptionEnum.getMsg());
-        this.code = exceptionEnum.getCode();
-    }
-
-    /**
-     * 自定义错误信息
-     * @param message
-     * @param code
-     */
-    public DescribeException(String message, Integer code) {
-        super(message);
-        this.code = code;
-    }
-
-    public Integer getCode() {
-        return code;
-    }
-
-    public void setCode(Integer code) {
-        this.code = code;
-    }
-}
-

+ 0 - 49
src/main/java/com/sqx/modules/file/utils/ExceptionEnum.java

@@ -1,49 +0,0 @@
-package com.sqx.modules.file.utils;
-
-public enum ExceptionEnum {
-    UNKNOW_ERROR(-1, "未知错误"),
-    LIMIT_USER(-100, "账号已经禁用,请联系管理员!"),
-    USER_NOT_FIND(-101, "用户未注册"),
-    USER_IS_BIND_FOR_ANTHER_OPENID(-99, "当前手机号已经被其他微信绑定"),
-    WRONT_TOKEN(-102, "用户信息失效,请重新登录"),
-    USER_PWD_EMPTY(-103, "用户名密码不能为空"),
-    USER_PWD_ERROR(-104, "用户名或密码错误"),
-    USER_IS_EXITS(-105, "手机号已经注册!"),
-    ERROR(-106, "服务器内部错误"),
-    UPDATE_PWD_ERROR(-107, "密码修改失败"),
-    STATE_PWD_ERROR(-108, "状态修改失败"),
-    DATA_EMPTY(-109, "添加数据不能为空"),
-    Return_ATA_EMPTY(-110, "暂无数据"),
-    ADD_ERROR(-111, "提现失败"),
-    CODE_ERROR(-112, "验证码不正确"),
-    BIND_ERROR(-113, "手机号已经被其他账号绑定"),
-    SEND_ERROR(-114, "验证码发送失败"),
-    USER_PHONE_ERROR(-115, "用户名不能为空"),
-    OLD_PWD_ERROR(-116, "原始密码错误"),
-    IS_REGISTER(-117, "当前手机号已经绑定其他微信账号"),
-    IS_BIND(-118, "当前淘宝账号已经绑定其他手机号"),
-    IS_BIND_RELATION(-119, "当前账号已经绑定其他淘宝账号"),
-    OLD_NOT_SAME_NEW_PWD_ERROR(-120, "新密码不能等于和原始密码一致"),
-    USER_IS_REGISTER(-121, "用户已经注册请前往登录"),
-    RELATIONID_IS_REGISTER(-122, "淘宝账号已经授权绑定其他手机号"),
-    CODE_NOT_FOUND(-123, "邀请码不存在"),
-    COMMON_IS_EXITS(-124, "已经存在"),
-    COUPONS_ZERO(-125, "优惠券被领完了"),
-    COUPONS_GET_OUT(-126, "优惠券超过领取次数"),
-    COUPONS_TIME_OUT(-127, "优惠券已过期");
-    private Integer code;
-    private String msg;
-    ExceptionEnum(Integer code, String msg) {
-        this.code = code;
-        this.msg = msg;
-    }
-
-    public Integer getCode() {
-        return code;
-    }
-
-    public String getMsg() {
-        return msg;
-    }
-}
-

+ 38 - 102
src/main/java/com/sqx/modules/file/utils/FileUploadUtils.java

@@ -1,10 +1,9 @@
 package com.sqx.modules.file.utils;
 
-import com.sqx.modules.common.service.CommonInfoService;
+import com.sqx.modules.chats.utils.DescribeException;
 import org.apache.commons.io.FilenameUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.time.DateFormatUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.File;
@@ -13,11 +12,10 @@ import java.util.Date;
 
 /**
  * 文件上传工具类
- * 
+ *
  * @author ruoyi
  */
-public class FileUploadUtils
-{
+public class FileUploadUtils {
     /**
      * 默认大小 50M
      */
@@ -30,53 +28,18 @@ public class FileUploadUtils
 
     private static int counter = 0;
 
-    private static CommonInfoService commonRepository;
-
-    @Autowired
-    public void setCommonRepository(CommonInfoService commonRepository) {
-        FileUploadUtils.commonRepository = commonRepository;
-    }
-
-    public static String getDefaultBaseDir()
-    {
-        return commonRepository.findOne(19).getValue();
-    }
-
-    /**
-     * 以默认配置进行文件上传
-     *
-     * @param file 上传的文件
-     * @return 文件名称
-     * @throws Exception
-     */
-    public static final String upload(MultipartFile file) throws IOException
-    {
-        try
-        {
-            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
-        }
-        catch (Exception e)
-        {
-            throw new IOException(e.getMessage(), e);
-        }
-    }
-
     /**
      * 根据文件路径上传
      *
      * @param baseDir 相对应用的基目录
-     * @param file 上传的文件
+     * @param file    上传的文件
      * @return 文件名称
      * @throws IOException
      */
-    public static final String upload(String baseDir, MultipartFile file) throws IOException
-    {
-        try
-        {
+    public static final String upload(String baseDir, MultipartFile file) throws IOException {
+        try {
             return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             throw new IOException(e.getMessage(), e);
         }
     }
@@ -85,16 +48,14 @@ public class FileUploadUtils
      * 文件上传
      *
      * @param baseDir 相对应用的基目录
-     * @param file 上传的文件
+     * @param file    上传的文件
      * @return 返回上传成功的文件名
      */
     public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
-    throws DescribeException,IOException
-    {
-        int fileNamelength = file.getOriginalFilename().length();
-        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
-        {
-            throw new DescribeException("文件名太长",-100);
+            throws DescribeException, IOException {
+        int fileNameLength = file.getOriginalFilename().length();
+        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
+            throw new DescribeException("文件名太长", -100);
         }
 
         assertAllowed(file, allowedExtension);
@@ -110,42 +71,35 @@ public class FileUploadUtils
     /**
      * 编码文件名
      */
-    public static final String extractFilename(MultipartFile file)
-    {
+    public static final String extractFilename(MultipartFile file) {
         String fileName = file.getOriginalFilename();
         String extension = getExtension(file);
-        fileName =datePath() + "/" + encodingFilename(fileName) + "." + extension;
+        fileName = datePath() + "/" + encodingFilename(fileName) + "." + extension;
         return fileName;
     }
 
     /**
      * 日期路径 即年/月/日 如2018/08/08
      */
-    public static final String datePath()
-    {
+    public static final String datePath() {
         Date now = new Date();
         return DateFormatUtils.format(now, "yyyy/MM/dd");
     }
 
 
-
-    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
-    {
+    private static File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
         File desc = new File(uploadDir + File.separator + fileName);
 
-        if (!desc.getParentFile().exists())
-        {
+        if (!desc.getParentFile().exists()) {
             desc.getParentFile().mkdirs();
         }
-        if (!desc.exists())
-        {
+        if (!desc.exists()) {
             desc.createNewFile();
         }
         return desc;
     }
 
-    private static final String getPathFileName(String uploadDir, String fileName) throws IOException
-    {
+    private static String getPathFileName(String uploadDir, String fileName) {
         int dirLastIndex = uploadDir.lastIndexOf("/") + 1;
         String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
         String pathFileName = "/file/" + currentDir + "/" + fileName;
@@ -155,8 +109,7 @@ public class FileUploadUtils
     /**
      * 编码文件名
      */
-    private static final String encodingFilename(String fileName)
-    {
+    private static String encodingFilename(String fileName) {
         fileName = fileName.replace("_", " ");
         fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
         return fileName;
@@ -169,36 +122,24 @@ public class FileUploadUtils
      * @return
      */
     public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
-            throws DescribeException
-    {
+            throws DescribeException {
         long size = file.getSize();
-        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
-        {
-            throw new DescribeException("文件太大",-100);
+        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
+            throw new DescribeException("文件太大", -100);
         }
 
-        String fileName = file.getOriginalFilename();
         String extension = getExtension(file);
-        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
-        {
-            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
-            {
-                throw new DescribeException("",-100);
-            }
-            else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
-            {
-                throw new DescribeException("",-100);
-            }
-            else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
-            {
-                throw new DescribeException("",-100);
-            }
-            else
-            {
-                throw new DescribeException("",-100);
+        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
+            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
+                throw new DescribeException("", -100);
+            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
+                throw new DescribeException("", -100);
+            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
+                throw new DescribeException("", -100);
+            } else {
+                throw new DescribeException("", -100);
             }
         }
-
     }
 
     /**
@@ -208,12 +149,9 @@ public class FileUploadUtils
      * @param allowedExtension
      * @return
      */
-    public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
-    {
-        for (String str : allowedExtension)
-        {
-            if (str.equalsIgnoreCase(extension))
-            {
+    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
+        for (String str : allowedExtension) {
+            if (str.equalsIgnoreCase(extension)) {
                 return true;
             }
         }
@@ -222,15 +160,13 @@ public class FileUploadUtils
 
     /**
      * 获取文件名的后缀
-     * 
+     *
      * @param file 表单文件
      * @return 后缀名
      */
-    public static final String getExtension(MultipartFile file)
-    {
+    public static final String getExtension(MultipartFile file) {
         String extension = FilenameUtils.getExtension(file.getOriginalFilename());
-        if (StringUtils.isEmpty(extension))
-        {
+        if (StringUtils.isEmpty(extension)) {
             extension = MimeTypeUtils.getExtension(file.getContentType());
         }
         return extension;

+ 0 - 137
src/main/java/com/sqx/modules/file/utils/FileUtils.java

@@ -1,137 +0,0 @@
-package com.sqx.modules.file.utils;
-
-import javax.servlet.http.HttpServletRequest;
-import java.io.*;
-import java.net.URLEncoder;
-
-/**
- * 文件处理工具类
- * 
- * @author ruoyi
- */
-public class FileUtils
-{
-    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
-
-    /**
-     * 输出指定文件的byte数组
-     * 
-     * @param filePath 文件路径
-     * @param os 输出流
-     * @return
-     */
-    public static void writeBytes(String filePath, OutputStream os) throws IOException
-    {
-        FileInputStream fis = null;
-        try
-        {
-            File file = new File(filePath);
-            if (!file.exists())
-            {
-                throw new FileNotFoundException(filePath);
-            }
-            fis = new FileInputStream(file);
-            byte[] b = new byte[1024];
-            int length;
-            while ((length = fis.read(b)) > 0)
-            {
-                os.write(b, 0, length);
-            }
-        }
-        catch (IOException e)
-        {
-            throw e;
-        }
-        finally
-        {
-            if (os != null)
-            {
-                try
-                {
-                    os.close();
-                }
-                catch (IOException e1)
-                {
-                    e1.printStackTrace();
-                }
-            }
-            if (fis != null)
-            {
-                try
-                {
-                    fis.close();
-                }
-                catch (IOException e1)
-                {
-                    e1.printStackTrace();
-                }
-            }
-        }
-    }
-
-    /**
-     * 删除文件
-     * 
-     * @param filePath 文件
-     * @return
-     */
-    public static boolean deleteFile(String filePath)
-    {
-        boolean flag = false;
-        File file = new File(filePath);
-        // 路径为文件且不为空则进行删除
-        if (file.isFile() && file.exists())
-        {
-            file.delete();
-            flag = true;
-        }
-        return flag;
-    }
-
-    /**
-     * 文件名称验证
-     * 
-     * @param filename 文件名称
-     * @return true 正常 false 非法
-     */
-    public static boolean isValidFilename(String filename)
-    {
-        return filename.matches(FILENAME_PATTERN);
-    }
-
-    /**
-     * 下载文件名重新编码
-     * 
-     * @param request 请求对象
-     * @param fileName 文件名
-     * @return 编码后的文件名
-     */
-    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
-            throws UnsupportedEncodingException
-    {
-        final String agent = request.getHeader("USER-AGENT");
-        String filename = fileName;
-        if (agent.contains("MSIE"))
-        {
-            // IE浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
-            filename = filename.replace("+", " ");
-        }
-        else if (agent.contains("Firefox"))
-        {
-            // 火狐浏览器
-            filename = new String(fileName.getBytes(), "ISO8859-1");
-        }
-        else if (agent.contains("Chrome"))
-        {
-            // google浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
-        }
-        else
-        {
-            // 其它浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
-        }
-        return filename;
-    }
-}

+ 12 - 15
src/main/java/com/sqx/modules/file/utils/MimeTypeUtils.java

@@ -2,11 +2,10 @@ package com.sqx.modules.file.utils;
 
 /**
  * 媒体类型工具类
- * 
+ *
  * @author ruoyi
  */
-public class MimeTypeUtils
-{
+public class MimeTypeUtils {
     public static final String IMAGE_PNG = "image/png";
 
     public static final String IMAGE_JPG = "image/jpg";
@@ -16,13 +15,13 @@ public class MimeTypeUtils
     public static final String IMAGE_BMP = "image/bmp";
 
     public static final String IMAGE_GIF = "image/gif";
-    
-    public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };
 
-    public static final String[] FLASH_EXTENSION = { "swf", "flv" };
+    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
 
-    public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
-            "asf", "rm", "rmvb" };
+    public static final String[] FLASH_EXTENSION = {"swf", "flv"};
+
+    public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
+            "asf", "rm", "rmvb"};
 
     public static final String[] DEFAULT_ALLOWED_EXTENSION = {
             // 图片
@@ -33,15 +32,13 @@ public class MimeTypeUtils
             "rar", "zip", "gz", "bz2",
             // 安卓ios更新包
             "apk", "ipa",
-            //视频格式
-            "mp4","mp3","3GP","AVI","mov","rmvb",
+            // 视频格式
+            "mp4", "mp3", "3GP", "AVI", "mov", "rmvb",
             // pdf
-            "pdf" };
+            "pdf"};
 
-    public static String getExtension(String prefix)
-    {
-        switch (prefix)
-        {
+    public static String getExtension(String prefix) {
+        switch (prefix) {
             case IMAGE_PNG:
                 return "png";
             case IMAGE_JPG:

+ 4 - 0
src/main/resources/application-dev.yml

@@ -81,6 +81,8 @@ secure-api:
             - /chatSocket/**
             - /websocket/**
             - /alioss/**
+            - /admin/new-file/**
+            - /app/new-file/**
             - /swagger-ui.html
             - /v2/api-docs
             - /swagger-resources/**
@@ -106,6 +108,8 @@ secure-api:
             - /chatSocket/**
             - /websocket/**
             - /alioss/**
+            - /admin/new-file/**
+            - /app/new-file/**
             - /swagger-ui.html
             - /v2/api-docs
             - /swagger-resources/**

+ 4 - 0
src/main/resources/application-prod.yml

@@ -78,6 +78,8 @@ secure-api:
             - /chatSocket/**
             - /websocket/**
             - /alioss/**
+            - /admin/new-file/**
+            - /app/new-file/**
             - /swagger-ui.html
             - /v2/api-docs
             - /swagger-resources/**
@@ -101,6 +103,8 @@ secure-api:
             - /chatSocket/**
             - /websocket/**
             - /alioss/**
+            - /admin/new-file/**
+            - /app/new-file/**
             - /swagger-ui.html
             - /v2/api-docs
             - /swagger-resources/**