package com.bxwell.ims.core.util;

import cn.hutool.core.codec.Base64Decoder;
import com.aliyun.oss.*;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

@Configuration
public class FileManagerUtil {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * oss文件上传
     */
    public String uploadFile(MultipartFile file) throws Exception {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        OSSClient ossClient = null;
        String fileName = null;
        String fileKey = null;
        URL signedUrl = null;
        try {
            fileName = file.getOriginalFilename();
            fileKey = "userInfo/" + UUID.randomUUID().toString() + "/" + fileName;
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret,clientConfiguration);
            ossClient.putObject(bucketName, fileKey, file.getInputStream());
            //生成访问地址
            Date expiration = DateUtil.parseRfc822Date("Wed, 1 Mar 2999 1:1:10 GMT");
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileKey, HttpMethod.GET);
            request.setExpiration(expiration);
            signedUrl = ossClient.generatePresignedUrl(request);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            ossClient.shutdown();
        }
        return signedUrl.toString();
    }

    private String handleFileName(String fileName){
        int userInfo = fileName.indexOf("userInfo");
        String substring = fileName.substring(userInfo, fileName.length() - 1);
        int i = substring.indexOf("?Expires");
        return substring.substring(0,i);
    }

    public void download(String objectName,String filename,HttpServletResponse response){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //特殊处理文件名加号
            objectName=objectName.replaceAll("\\+", "%2B");
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, handleFileName(URLDecoder.decode(objectName,"utf-8")));
            // 读取文件内容
            BufferedInputStream reader=new BufferedInputStream(ossObject.getObjectContent());
            //System.out.println(ossObject.getObjectContent().toString());
            BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));

            byte[] car=new byte[1024];
            int L=0;
            while((L=reader.read(car))!=-1){
                out.write(car, 0,L);
            }
            if(out!=null){
                out.flush();
                out.close();
            }
            // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
            if(reader!=null){
                reader.close();
            }
            // ossObject对象使用完毕后必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
            ossObject.close();

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * oss文件上传
     */
    public String uploadFileForBase64(String base64) throws Exception {
        OSSClient ossClient = null;
        String fileName = null;
        String fileKey = null;
        URL signedUrl = null;
        try {
            byte[] bytes = Base64.decodeBase64(base64);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            fileKey = "userInfo/" + UUID.randomUUID().toString() + "/" + UUID.randomUUID().toString() + ".png";
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileKey, inputStream);

            //生成访问地址
            Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 5 );
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileKey, HttpMethod.GET);
            request.setExpiration(expiration);
            signedUrl = ossClient.generatePresignedUrl(request);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            ossClient.shutdown();
        }
        return signedUrl.toString();
    }

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐