阿里云OSS服務(wù) java對接

OssUtil.java


@Slf4j
@Component
public class OssUtil {
    /**
     * EtpConfig->service模塊
     * util無法獲取
     */
    private static String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
    private static String accessKeyId = "accessKeyId ";
    private static String accessKeySecret = "accessKeySecret ";
    private static String bucketName = "bucketName ";

    /**
     * 上傳文件-文件夾拼接(a/b/c/+filename)(流的形式-ecs免流量)
     * @param inputStream 文件流
     * @param folder 文件夾
     * @param fileName 文件名字(保留后綴)
     * @return 保存的文件key
     */
    public static String uploadObjectByInputStream(InputStream inputStream, String folder, String fileName){
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //folder+/+fileName
        String key;
        if(StringUtils.isEmpty(folder)){
            key = fileName;
        }else{
            key = folder + fileName;
        }
        try{
            client.putObject(bucketName, key, inputStream);
        }catch (Exception e){
            throw e;
        }finally {
            client.shutdown();
        }
        return key;
    }

    /**
     * 上傳文件-全路徑(a/b/c/filename)(流的形式-ecs免流量)
     * @param inputStream 文件流
     * @param fileFullPath 文件全路徑(保留后綴)
     * @return 保存的文件key
     */
    public static String uploadObjectByInputStream(InputStream inputStream, String fileFullPath) throws Exception{
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try{
            client.putObject(bucketName, fileFullPath, inputStream);
        }catch (Exception e){
            throw e;
        }finally {
            client.shutdown();
        }
        return fileFullPath;
    }

    /**
     * 通過oss->File->key值 獲取對應(yīng)文件的流(字節(jié)-網(wǎng)絡(luò)傳輸)
     * @param fileKey
     * @return
     */
    public static byte[] getFileByteByKey(String fileKey) throws Exception {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = null;
        byte[] result = null;
        try {
            OSSObject ossObject = client.getObject(bucketName, fileKey);
            inputStream = ossObject.getObjectContent();
            result = toByteArray(inputStream);
        }catch (Exception e){
            throw e;
        }finally {
            try{
                if(inputStream!=null){
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            client.shutdown();
        }
        return result;
    }

   /**
     * 通過key值 獲取對應(yīng)文件的流(InputStream)
     * 實(shí)際上這個方法是無效的(client.shutdwon()會將流關(guān)閉 )
     * 所以可以這里進(jìn)行流的操作 (比如可以參見:getFileByteByKey())
     * 把流讀取到可以被保存的數(shù)據(jù)媒介中
     * @param fileKey
     * @return
     */
    @Deprecated
    public static InputStream getFileInputStreamByKey(String fileKey) {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = null;
        try {
            OSSObject ossObject = client.getObject(bucketName, fileKey);
            inputStream = ossObject.getObjectContent();
        }catch (Exception e){
            throw e;
        }finally {
            try{
                if(inputStream!=null){
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            client.shutdown();
        }
        return inputStream;
    }


    /**
     * 根據(jù)文件名獲取文件訪問URL(外網(wǎng)訪問-下行收費(fèi))
     * @param ossFileKey 文件名
     * @param expires URL有效時(shí)間(小時(shí))
     * @return
     */
    public static String getFileUrl(String ossFileKey, int expires) {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        URL url = client.generatePresignedUrl(bucketName, ossFileKey, dateAfter(new Date(), expires, Calendar.HOUR));
        String path = url.toString();
        return path;
    }


    /**
     * 原圖生成縮略圖url
     * @param ossFileKey
     * @return
     */
    public static String getSltFileUrl(String ossFileKey,String centerName) throws IOException {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        /**
         * 控制臺設(shè)置的圖片處理的style或者默認(rèn)style
         */
        String style = "image/auto-orient,1/resize,m_lfit,w_100/quality,q_90";
        GetObjectRequest request = new GetObjectRequest(bucketName,ossFileKey);
        request.setProcess(style);
        OSSObject ossObject = client.getObject(request);
        InputStream inputStream = ossObject.getObjectContent();
        String suffix = ossFileKey.substring(ossFileKey.lastIndexOf("."));
        String name = ossFileKey.substring(0,ossFileKey.lastIndexOf("."));
        String sltName = name+centerName+suffix;
        System.out.println(sltName);
        try{
            client.putObject(bucketName, sltName, inputStream);
        }catch (Exception e){
            throw e;
        }finally {
            client.shutdown();
        }
        return sltName;
    }


    /**
     * (private)input轉(zhuǎn)字節(jié)
     * @param input
     * @return
     * @throws Exception
     */
    private static byte[] toByteArray(InputStream input) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * (private)獲得指定日期之后一段時(shí)期的日期。例如某日期之后3天的日期等。
     * @param origDate 基準(zhǔn)日期
     * @param amount 基準(zhǔn)日期
     * @param timeUnit 時(shí)間單位,如年、月、日等。用Calendar中的常量代表
     * @return
     */
    private static final Date dateAfter(Date origDate, int amount, int timeUnit) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(origDate);
        calendar.add(timeUnit, amount);
        return calendar.getTime();
    }

}

controller

@RestController
@RequestMapping("/fileOss")
@Slf4j
public class FileOssController {

    @Autowired
    private OssUtil ossUtil;

    @RequestMapping("/upload")
    @ResponseBody
    public R uploadFile(@RequestParam("images") MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        //String caselsh = filename.substring(0,filename.lastIndexOf("."));
        //String suffix = filename.substring(filename.lastIndexOf(".")+1);
        String fileKey = ossUtil.uploadObjectByInputStream(file.getInputStream(),filename);
        Map<String,Object> params = new HashMap<>();
        params.put("fileKey",fileKey);
        return R.ok(params);
    }

    /**
     * 通過fileKey獲取oss流數(shù)據(jù)并返回
     * @param ossFileKey
     * @return
     */
    @RequestMapping("/getByteByOssFileKey")
    @ResponseBody
    public byte[] getByteByOssFileKey(@RequestParam("ossFileKey") String ossFileKey) throws Exception{
        return ossUtil.getFileByteByKey(ossFileKey);
    }

    /**
     * 通過fileKey獲取oss文件的url 測試接口3
     * @param ossFileKey
     * @return
     */
    @RequestMapping("/getUrlByOssFileKey")
    @ResponseBody
    public R getUrlByOssFileKey(@RequestParam String ossFileKey){
        String url = ossUtil.getFileUrl(ossFileKey,24);
        Map<String,Object> params = new HashMap<>();
        params.put("fileurl",url);
        return R.ok(params);
    }

}

部分接口訪問的例子 .html

<img id="imgReturn" src="/fileOss/getByteByOssFileKey?ossFileKey=XXX">
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容