FileUploadUtils.java 15.6 KB
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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
package com.bs.common.utils.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.bs.common.config.CosConfig;
import com.bs.common.config.BsChatConfig;
import com.bs.common.constant.Constants;
import com.bs.common.enums.FileCosType;
import com.bs.common.exception.file.FileNameLengthLimitExceededException;
import com.bs.common.exception.file.FileSizeLimitExceededException;
import com.bs.common.exception.file.InvalidExtensionException;
import com.bs.common.utils.DateUtils;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.uuid.IdUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具类
 *
 * @author system
 */
@Slf4j
public class FileUploadUtils {
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

//    /**
//     * 默认上传的地址
//     */
//    private static String defaultBaseDir = LinkWeChatConfig.getProfile();
//
//    public static void setDefaultBaseDir(String defaultBaseDir) {
//        FileUploadUtils.defaultBaseDir = defaultBaseDir;
//    }
//
//    public static String getDefaultBaseDir() {
//        return defaultBaseDir;
//    }



//    /**
//     * 以默认配置进行文件上传
//     *
//     * @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);
//        }
//    }
//
//    public static final String upload(InputStream inputStream,String fileName) throws IOException {
//        try {
//            return upload(getDefaultBaseDir(), inputStream, fileName);
//        } catch (Exception e) {
//            throw new IOException(e.getMessage(), e);
//        }
//    }
//
//
//    /**
//     * 以默认配置进行文件上传
//     *
//     * @param file 上传的文件
//     * @return 文件名称
//     * @throws Exception
//     */
//    public static final String uploadFile(MultipartFile file) throws IOException {
//        try {
//            return uploadFile(getDefaultBaseDir(), file);
//        } catch (Exception e) {
//            throw new IOException(e.getMessage(), e);
//        }
//    }
//
    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = getPathFileName(baseDir, fileName);
        return pathFileName;
    }

    public static final String upload(String baseDir, InputStream inputStream, String fileName) throws IOException {
        File desc = getAbsoluteFile(baseDir, fileName);
        File file = FileUtil.writeFromStream(inputStream, desc);
        return file.getAbsolutePath();
    }

    /**
     * 上传到腾讯对象云存储中
     *
     * @param file    上传的文件
     * @return 访问路径
     * @throws IOException
     */
    public static final String uploadTenantCos(MultipartFile file , CosConfig cosConfig) throws IOException {
        try {
            return uploadCos( file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION,cosConfig,FileCosType.FILE_COS_TYPE_TENANT.getType());
        } catch (Exception e) {
            log.error("上传文件异常:",e);
            throw new IOException(e.getMessage(), e);
        }
    }


    /**
     * 上传阿里云存储中
     * @param file
     * @param cosConfig
     * @return
     */
    public static final String uploadAliOss(MultipartFile file , CosConfig cosConfig) throws IOException {

        try {
            return uploadCos( file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION,cosConfig,FileCosType.FILE_COS_TYPE_ALI.getType());
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }

    }







//    /**
//     * 通过流进行文件上传
//     * @param in 流
//     * @throws IOException
//     */
//    public static String uploadTenantCos(InputStream in, String fileExtension, CosConfig cosConfig) throws IOException {
//        try {
//            return uploadTenantCos( in, fileExtension, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, cosConfig);
//        } catch (Exception e) {
//            throw new IOException(e.getMessage(), e);
//        }
//    }


    /**
     * 文件上传
     *
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String uploadCos(MultipartFile file, String[] allowedExtension, CosConfig cosConfig,Integer fileCosType)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            log.error("文件名太长");
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);


        if(FileCosType.FILE_COS_TYPE_TENANT.getType().equals(fileCosType)){//腾讯云存储逻辑
            // 1 初始化用户身份信息(secretId, secretKey)。
            COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
            // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
            Region region = new Region(cosConfig.getRegion());
            ClientConfig clientConfig = new ClientConfig(region);
            // 3 生成 cos 客户端。
            COSClient cosClient = new COSClient(cred, clientConfig);

            // 指定要上传到 COS 上对象键
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), fileName,file.getInputStream(),objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info("{}",cosConfig.getCosImgUrlPrefix()+fileName);
            log.info("腾讯cos上传信息:{}",new ObjectMapper().writeValueAsString(putObjectResult));
            cosClient.shutdown();

        }else if(FileCosType.FILE_COS_TYPE_ALI.getType().equals(fileCosType)){//阿里云存储逻辑

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(cosConfig.getRegion(), cosConfig.getSecretId(), cosConfig.getSecretKey());


            // 上传文件
            ossClient.putObject(cosConfig.getBucketName(), fileName, file.getInputStream());
            ossClient.shutdown();
        }
//        else if(FileCosType.FILE_COS_TYPE_QN.getType().equals(fileCosType)){ //七牛云存储
//
//            // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//            Configuration cfg = new Configuration(Zone.zone0());
//            // ...其他参数参考类注释
//            UploadManager uploadManager = new UploadManager(cfg);
//
//
//
//
//        }



        return fileName;
    }

//    /**
//     * 将流中的文件传到腾讯云
//     * @param inputStream 输入流
//     * @param fileExtension 被写入流的文件的后缀名
//     * @param allowedExtension 允许的后缀名
//     * @throws FileSizeLimitExceededException 文件大小超过上限
//     * @throws InvalidExtensionException 文件后缀名非法
//     */
//    public static String uploadTenantCos(InputStream inputStream, String fileExtension, String[] allowedExtension, CosConfig cosConfig) throws FileSizeLimitExceededException, InvalidExtensionException {
//        String fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + fileExtension;
//        if (!isAllowedExtension(fileExtension, allowedExtension))
//        {
//            throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, fileExtension, fileName);
//        }
//        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
//        Region region = new Region(cosConfig.getRegion());
//        ClientConfig clientConfig = new ClientConfig(region);
//        COSClient cosClient = new COSClient(cred, clientConfig);
//        ObjectMetadata objectMetadata = new ObjectMetadata();
//        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), fileName ,inputStream ,objectMetadata);
//        cosClient.putObject(putObjectRequest);
//        cosClient.shutdown();
//        return fileName;
//    }


//    public static final String uploadFile(String baseDir, MultipartFile file)
//            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException {
//        int fileNamelength = file.getOriginalFilename().length();
//        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
//            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
//        }
//
//        String fileName = extractFilename(file);
//
//        File desc = getAbsoluteFile(baseDir, fileName);
//        file.transferTo(desc);
//        String pathFileName = getPathFileName(baseDir, fileName);
//        return pathFileName;
//    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
        return fileName;
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = BsChatConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName;
        if(org.apache.commons.lang3.StringUtils.isBlank(currentDir)){
            pathFileName = Constants.RESOURCE_PREFIX + "/" +fileName;
        }else {
            pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        }
        return pathFileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}