All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yes.tools.utils.OssUtils Maven / Gradle / Ivy

There is a newer version: 2.0.4
Show newest version
package org.yes.tools.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.yes.tools.core.exception.YesBaseException;
import org.yes.tools.core.properties.AliProperties;
import org.yes.tools.core.vo.ImageVo;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/***
 * 文件上传工具类
 *
 * @author Co.
 * @date: 2022/10/22 13:31
 * @return
 */
@Slf4j
public class OssUtils {

    /***
     * 阿里云文件上传
     *
     * @author Co.
     * @date: 2022/9/2 18:44
     * @return
     */
    public static ImageVo ordinaryUpload(MultipartFile file, String filePath, String bucketName) throws IOException {
        ImageVo vo = new ImageVo();

        //获取文件名称
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //组成文件储存路径
        String datePath = filePath + "/" + cn.hutool.core.date.DateUtil.today() + "/" + uuid + "." + suffix;

        OSS aliOss = SpringUtil.getBean(OSS.class);
        InputStream inputStream = file.getInputStream();
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //设置Content-disposition的内容模板格式,基于base64编码格式
            String downloadFileNameTemplate = "attachment; filename=\"=?UTF8?B?%s?=\"";
            //对真正文件名称进行base64编码
            String base64FileName = new String(Base64.getEncoder().encode(fileName.getBytes(StandardCharsets.UTF_8)));
            //设置下载文件的名称
            objectMetadata.setContentDisposition(String.format(downloadFileNameTemplate, base64FileName));
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, datePath, inputStream, objectMetadata);
            // 创建PutObject请求。
            aliOss.putObject(putObjectRequest);
            vo.setUrl("/" + datePath);
            vo.setFileName(fileName);
            inputStream.close();
            return vo;
        } catch (OSSException oe) {
            log.info(oe.getMessage());
        } catch (ClientException ce) {
            log.info(ce.getMessage());
        }
        return null;
    }

    /**
     * 分片上传
     *
     * @param file
     * @param filePath
     * @param bucketName
     * @return
     * @throws IOException
     */
    public static CompleteMultipartUploadResult burstUpload(File file, String filePath, String bucketName) throws IOException {

        //获取文件名称
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //组成文件储存路径
        String datePath = filePath + "/" + cn.hutool.core.date.DateUtil.today() + "/" + uuid + "." + suffix;

        OSS aliOss = SpringUtil.getBean(OSS.class);
        try {
            // 创建InitiateMultipartUploadRequest对象。
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, datePath);

            // 如果需要在初始化分片时设置请求头,请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());

            String downloadFileNameTemplate = "attachment; filename=\"=?UTF8?B?%s?=\"";
            //对真正文件名称进行base64编码
            String base64FileName = new String(Base64.getEncoder().encode(fileName.getBytes(StandardCharsets.UTF_8)));
            //设置下载文件的名称
            metadata.setContentDisposition(String.format(downloadFileNameTemplate, base64FileName));
            request.setObjectMetadata(metadata);

            // 初始化分片。
            InitiateMultipartUploadResult upresult = aliOss.initiateMultipartUpload(request);
            // 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。
            String uploadId = upresult.getUploadId();
            // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。
            List partETags = new ArrayList();
            // 每个分片的大小,用于计算文件有多少个分片。单位为字节。
            final long partSize = Integer.parseInt(AliProperties.PART_SIZE) * 1024 * 1024L;
            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
            long fileLength = file.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            // 遍历分片上传。
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                InputStream instream = new FileInputStream(file);
                // 跳过已经上传的分片。
                instream.skip(startPos);
                UploadPartRequest uploadPartRequest = new UploadPartRequest();
                uploadPartRequest.setBucketName(bucketName);
                uploadPartRequest.setKey(datePath);
                uploadPartRequest.setUploadId(uploadId);
                uploadPartRequest.setInputStream(instream);
                // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。
                uploadPartRequest.setPartSize(curPartSize);
                // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。
                uploadPartRequest.setPartNumber(i + 1);
                // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。
                UploadPartResult uploadPartResult = aliOss.uploadPart(uploadPartRequest);
                // 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。
                partETags.add(uploadPartResult.getPartETag());
            }

            // 创建CompleteMultipartUploadRequest对象。
            // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, datePath, uploadId, partETags);
            // 完成分片上传。
            CompleteMultipartUploadResult completeMultipartUploadResult = aliOss.completeMultipartUpload(completeMultipartUploadRequest);
            return completeMultipartUploadResult;
        } catch (OSSException oe) {
            log.info(oe.getMessage());
        } catch (ClientException ce) {
            log.info(ce.getMessage());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param bucketName
     * @return
     * @throws IOException
     */
    public static InputStream download(String filePath, String bucketName) {
        // 创建OSSClient实例。
        OSS ossClient = SpringUtil.getBean(OSS.class);
        try {
            // 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, filePath);
            // 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
            InputStream content = ossObject.getObjectContent();
            if (content != null) {
                return content;
            }
            return null;
        } catch (OSSException oe) {
            throw new YesBaseException(oe.getMessage());
        } catch (ClientException ce) {
            throw new YesBaseException(ce.getMessage());
        }
    }

    /**
     * 发送阿里云短信
     *
     * @param phone
     * @param code
     * @return
     * @throws com.aliyuncs.exceptions.ClientException
     */
    public static boolean sendAliSms(String phone, String code) throws com.aliyuncs.exceptions.ClientException {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliProperties.ACCESS_KEY_ID, AliProperties.ACCESS_KEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        //接收短信的手机号码
        request.setPhoneNumbers(phone);
        request.setSignName(AliProperties.SIGN_NAME);
        request.setTemplateCode(AliProperties.TEMPLATE_CODE);
        try {
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse response = client.getAcsResponse(request);
            if ("OK".equals(response.getCode())) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ClientException e) {
            throw new YesBaseException("短信发送失败");
        }
        return false;
    }

    /**
     * 发送阿里云短信
     *
     * @param phone
     * @param signName
     * @param templateCode
     * @param templateParam
     * @return
     * @throws com.aliyuncs.exceptions.ClientException
     */
    public static boolean sendAliSms(String phone, String signName, String templateCode, String templateParam) throws com.aliyuncs.exceptions.ClientException {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliProperties.ACCESS_KEY_ID, AliProperties.ACCESS_KEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        //接收短信的手机号码
        request.setPhoneNumbers(phone);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        try {
            request.setTemplateParam(templateParam);
//            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse response = client.getAcsResponse(request);
            if ("OK".equals(response.getCode())) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ClientException e) {
            throw new YesBaseException("短信发送失败");
        }
        return false;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy