Java集成华为云对象存储

1.maven添加依赖

<dependency>
            <groupId>com.huaweicloud</groupId>
            <artifactId>esdk-obs-java-bundle</artifactId>
            <version>[3.21.11,)</version>
        </dependency>

2.添加utils工具类

package com.neixunbao.platform.qcloud;

import com.obs.services.model.ObsObject;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import org.springframework.web.multipart.MultipartFile;

import com.obs.services.ObsClient;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Author: 榴莲豆包
 * @Date: 2022年7月2日15:19:49
 * @Description: java实现华为云文件上传(COSClient)
 * @REGIONID 区域
 * @KEY  上传上云之后的名字
 */
public class OBSHandler {
    //
    private final static String endPoint = "endPoint ";
    private final static String ak = "ak";
    private final static String sk = "sk";

    private final static String bucketname = "桶名称";

    private final static String BASEURL1 = "外网cdn地址,保存成功往数据库存的地址";

    // 创建 TransferManager 实例,这个实例用来后续调用高级接口
    static ObsClient createTransferManager() {
        // 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
        // 详细代码参见本页: 简单操作 -> 创建 COSClient
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        return obsClient;
    }
    static void shutdownTransferManager(ObsClient obsClient) {
        try {
            obsClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 上传文件---imgFile类型
     *
     * @return
     */
    public static String uploadFile(MultipartFile imgFile, HttpServletRequest request) {
        //转为File
        String filename = imgFile.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
        String path=request.getSession().getServletContext().getRealPath("/filetool");//生成一个目录
        String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
        String fileName = uuid+"."+prefix; //文件全路径
        File file=new File(path,fileName);
        //如果path路径不存在,创建一个文件夹
        if(!file.exists()){
            file.mkdirs();
        }
        ObsClient obsClient = createTransferManager();
        try {
            imgFile.transferTo(file);//没有这句话,生成的文件就是一个文件夹。有了以后,就会在path路径下,生成一个文件
            // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
            obsClient.putObject(bucketname,"uploadfile/"+fileName, file);
            dfsdelete(file.getPath());
            return BASEURL1+fileName;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            shutdownTransferManager(obsClient);
        }
        return "";
    }


    /**
     * 上传文件---直接传file
     *
     * @return
     */
    public static String uploadFile(File file) {
        //转为File
        String filename = file.getName();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
        String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
        String fileName = uuid+"."+prefix; //文件全路径
        ObsClient obsClient = createTransferManager();
        try {
            // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
            obsClient.putObject(bucketname,"uploadfile/"+fileName, file);
            return BASEURL1+fileName;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            shutdownTransferManager(obsClient);
        }
        return "";
    }

    /**
     * 上传文件---byte类型
     *
     * @return
     */
    public static String uploadFile(byte data[], String fileName) {
        //转为File
        InputStream inputStream = new ByteArrayInputStream(data);
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);//后缀
        String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
        fileName = uuid+"."+prefix; //文件全路径
        ObsClient obsClient = createTransferManager();
        try {
            // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
            obsClient.putObject(bucketname,"uploadfile/"+fileName, inputStream);
            return BASEURL1+fileName;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            shutdownTransferManager(obsClient);
        }
        return "";
    }

    /**
     * 下载ObsObject
     * @param filePath   需要下载的文件路径。 例:"site/a.txt"
     * @return  下载文件的字节数组
     * @throws IOException
     */
    public byte[] getFileByteArray(String filePath) throws IOException {
        ObsClient obsClient = createTransferManager();
        ObsObject obsObject = obsClient.getObject(bucketname, "uploadfile/"+filePath);
        InputStream input = obsObject.getObjectContent();
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        while ((len = input.read(b)) != -1){
            bos.write(b, 0, len);
        }
        bos.close();
        input.close();
        return bos.toByteArray();
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public static void deleteFile(String path) {

        ObsClient obsClient = createTransferManager();
        try {
            File file = new File(path);
            // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
            // 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324)
            String key = file.getName();
            obsClient.deleteObject(bucketname, "uploadfile/"+key);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }finally {
            shutdownTransferManager(obsClient);
        }

    }



    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String originalfileName) {
        String filePath = "test/";
        //1.获取后缀名 2.去除文件后缀 替换所有特殊字符

        return filePath;
    }

    public static void dfsdelete(String path) {
        File file=new File(path);
        if(file.isFile()) {//如果此file对象是文件的话,直接删除
            file.delete();
            return;
        }
        //当 file是文件夹的话,先得到文件夹下对应文件的string数组 ,递归调用本身,实现深度优先删除
        String [] list=file.list();
        for (int i = 0; i < list.length; i++) {
            dfsdelete(path+File.separator+list[i]);

        }//当把文件夹内所有文件删完后,此文件夹已然是一个空文件夹,可以使用delete()直接删除
        file.delete();
        return;
    }


    /**
     * 得到文件流
     * @param url  网络图片URL地址
     * @return
     */
    public static byte[] getFileStream(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * file转byte
     */
    public static byte[] file2byte(File file){
        byte[] buffer = null;
        try{
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * byte 转file
     */
    public static File byte2File(byte[] buf, String filePath, String fileName){
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try{
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()){
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }catch (Exception e){
            e.printStackTrace();
        }
        finally{
            if (bos != null){
                try{
                    bos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try{
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
    /**
     * multipartFile转File
     **/
    public static File multipartFile2File(MultipartFile multipartFile){
        File file = null;
        if (multipartFile != null){
            try {
                file=File.createTempFile("tmp", null);
                multipartFile.transferTo(file);
                System.gc();
                file.deleteOnExit();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return file;
    }

}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Java SDK 来实现华为云对象存储OBS的文件上传。以下是一个简单的示例代码: ```java import java.io.File; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.PutObjectResult; public class ObsUploadDemo { public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, ObsException, IOException { // 创建ObsClient对象 ObsClient obsClient = new ObsClient("yourAccessKeyId", "yourSecretAccessKey", "yourEndpoint"); // 设置bucket名称和对象名称 String bucketName = "yourBucketName"; String objectKey = "yourObjectName"; // 设置本地文件路径 String filePath = "yourLocalFilePath"; // 上传文件 File file = new File(filePath); PutObjectResult result = obsClient.putObject(bucketName, objectKey, file); // 打印上传结果 System.out.println("请求ID:" + result.getRequestId()); System.out.println("ETag:" + result.getEtag()); // 关闭ObsClient对象 obsClient.close(); } } ``` 其中,`yourAccessKeyId` 和 `yourSecretAccessKey` 分别是你的华为云账号的Access Key ID 和 Secret Access Key;`yourEndpoint` 是你的OBS服务的访问域名;`yourBucketName` 是你要上传的存储桶名称;`yourObjectName` 是你要上传的对象名称;`yourLocalFilePath` 是你要上传的本地文件路径。 注意,以上代码仅作为示例,实际使用时需要根据你的具体情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值