oss文件上传与下载

上传:如何使用流式上传和文件上传方式上传文件_对象存储 OSS-阿里云

package com.vazyme.kf.client.aliyun.oss.manager;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.SimplifiedObjectMeta;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@RefreshScope  // 会监听变化实时变化值
public class OssManager {

    @Value("${third.aliyun.oss.endpoint:''}")
    private String endpoint;
    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    @Value("${third.aliyun.oss.accessKeyId:''}")
    private String accessKeyId;
    @Value("${third.aliyun.oss.accessKeySecret:''}")
    private String accessKeySecret;
    // 填写Bucket名称,例如examplebucket。
    @Value("${third.aliyun.oss.bucketName:''}")
    private String bucketName;


    @Value("${file.baseUrl:''}")
    private String prePath;


    /**
     * 写入文件到oss
     * @author pengbin 
     * @date 2022/4/12 14:48
     * @param    objectName 文件名
     * @param sb 文件流
     * @return
     */
    public void writeOss(String objectName,StringBuffer sb){

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
//        File file = new File("D:\\opt\\upload\\vazyme-qr\\01\\012022040511242313812.txt");
//        String objectName = prePath + "/test" + file.getName();
        try {
            // 创建PutObjectRequest对象。
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 填写字符串。

            // 上传文件。
//            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
            // 上传文件。
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(sb.toString().getBytes()));
            ossClient.putObject(putObjectRequest);

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 写入文件到oss
     * @author pengbin 
     * @date 2022/4/12 17:45
     * @param
     * @return
     */
    public void writeFileOss(String objectName,String filePath){

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
//        File file = new File("D:\\opt\\upload\\vazyme-qr\\01\\012022040511242313812.txt");
//        String objectName = prePath + "/test" + file.getName();
        try {
            // 创建PutObjectRequest对象。
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 填写字符串。

            // 上传文件。
//            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
            // 上传文件。
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            ossClient.putObject(putObjectRequest);

        } catch (Exception e){
            throw e;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }



    /**
     * 获取文件信息
     * @author pengbin 
     * @date 2022/4/12 15:00
     * @param
     * @return
     */
    public String getSimplifiedObjectMeta(String filePath){
        String fileSize = "";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, filePath);
            fileSize = String.valueOf(objectMeta.getSize());
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("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.");
            log.error("Error Message:" + ce.getMessage());
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileSize;
    }

    /**
     * 文件下载,获取文件信息
     * @author pengbin 
     * @date 2022/4/12 15:06
     * @param
     * @return
     */
    public void download(String fileName, String filePath, HttpServletResponse response){

          /* InputStream in = new FileInputStream(new File(batchDO.getFileUrl()));//将该文件加入到输入流之中
        byte[] body = null;
        body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
        in.read(body);//读入到输入流里面*/

//        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-msdownload");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject  = ossClient.getObject(bucketName, filePath);

            BufferedInputStream input = new BufferedInputStream(ossObject.getObjectContent());
            byte[] buffBytes = new byte[1024];
            OutputStream outputStream  = response.getOutputStream();
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                outputStream.write(buffBytes, 0, read);
            }
            outputStream.flush();

            // 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 - 阿里云

 @GetMapping("/file/downLoad")
    @ResponseBody
    public void downLoad(@NotBlank(message = "批次id不能为空") String batchNo, HttpServletResponse response) {
        batchBizManager.downloadFile(batchNo,response);
    }

你可能感兴趣的:(java,java,oss)