当前位置:   article > 正文

华为云obs上传下载_华为云obs文件上传下载

华为云obs文件上传下载

华为云obs上传下载粘贴复制即可使用

package com.shie.idiThird.untils;


import com.obs.services.ObsClient;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.ObsObject;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;

@Component
@Slf4j
@RefreshScope
public class ObsUtil {

    private static String ENDPOINT = null;

    private static String AK = null;

    private static String SK = null;

    private static String BUCKET = null;
    @Value("${obs.ak}")
    private String ak;
    @Value("${obs.sk}")
    private String sk;
    @Value("${obs.endPoint}")
    private String endPoint;
    @Value("${obs.bucket}")
    private String bucket;
    @PostConstruct
    public void init() {
        ENDPOINT = endPoint;
        AK = ak;
        SK = sk;
        BUCKET = bucket;
    }
    /**
     * 文件上传
     *
     * @return
     */
    public static String upload(InputStream inputStream, String originalFilename, String uuidFileName) {
        log.info("======================>>进入obs上传<<====================");
        uuidFileName = "idi" + "/" + uuidFileName;
        ObsClient obsClient = null;
        //上传图片
        try {
            //获取流对象
            // 创建ObsClient实例
            obsClient = new ObsClient(AK, SK, ENDPOINT);
            //设置下载时,文件名称为原文件名
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //显示文件名过滤特殊字符
            originalFilename = IDIStringUtil.filterSpecialChar(originalFilename, "\\,/,:,*,?,\",<,>,|");
            String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            originalFilename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
//            objectMetadata.setContentDisposition("attachment;filename=" + UriUtils.encode(originalFilename, "UTF-8") + "." + type);
            objectMetadata.setContentDisposition("attachment;filename=" + UriUtils.encode(originalFilename, "UTF-8") + "." + type);
            // 使用访问OBS
            obsClient.putObject(BUCKET, uuidFileName, inputStream, objectMetadata);
            //将图片信息封装起来,方便前端回显调用
            return uuidFileName;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } finally {
            try {
                if (obsClient != null) {
                    // 关闭obsClient
                    obsClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("obs客户端流对象关闭失败!");
            }

        }
        return null;
    }

    //文件下载
    public String downloadImg() {
        TemporarySignatureRequest request = new TemporarySignatureRequest();
        request.setBucketName(bucket);
        request.setObjectKey("objectKey");
        request.setRequestDate(new Date());
        // 1分钟后链接失效
        request.setExpires(60);

        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        // 通过临时授权,直接访问链接下载
        TemporarySignatureResponse signature = obsClient.createTemporarySignature(request);
        log.info("download signedUrl-> {}", signature.getSignedUrl());
        return signature.getSignedUrl();
    }

    public static String getFileUrl(String fileName) {
        log.info("======================>>进入obs下载<<====================");
        TemporarySignatureRequest request = new TemporarySignatureRequest();

        request.setBucketName(BUCKET);
        request.setObjectKey(fileName);
        ObsClient obsClient = new ObsClient(AK, SK, ENDPOINT);

        // 1天后链接失效
        request.setExpires(86400);
        ObjectMetadata objectMetadata = obsClient.getObjectMetadata(BUCKET, fileName);
        log.info("======================>>objectMetadata"+objectMetadata+"<<====================");
        String contentDisposition = objectMetadata.getContentDisposition();
        ObsObject obsObject = obsClient.getObject(BUCKET, fileName);
        ObjectMetadata metadata = obsObject.getMetadata();
        log.info("======================>>metadata"+metadata+"<<====================");
        log.info("======================>>"+contentDisposition+"<<====================");
        //返回上传文件下载路径
        TemporarySignatureResponse signature = obsClient.createTemporarySignature(request);
        log.info("文件下载地址为:{}", signature.getSignedUrl());
        return signature.getSignedUrl();
    }
    /**
     * 下载oos文件流
     * @param fileId     文件id
     * @param showName   文件显示名称
     * @param response
     * @throws IOException
     */
    public static void getFileOutputStream(String fileId, String showName, HttpServletResponse response){
        log.info("======================>>进入obs<<====================");
        ObsClient obsClient = new ObsClient(AK, SK, ENDPOINT);
        ObsObject obsObject = obsClient.getObject(BUCKET, fileId);
        InputStream is = obsObject.getObjectContent();
        getFileOutputStream(showName, response, is);
    }




    public static void getFileOutputStream(String showName, HttpServletResponse response, InputStream is) {

        try {
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader(
                    "Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(showName, "UTF-8"));
            try (
                    BufferedInputStream bis = new BufferedInputStream(is);
                    // 输出流
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ) {
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = bis.read(buff)) > 0) {
                    bos.write(buff, 0, len);
                }
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }

}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/738753
推荐阅读
相关标签
  

闽ICP备14008679号