百度云上传文件工具类BosUtils

**

## BosUtils工具类

**

public class BosUtils {

    private static Logger logger = LoggerFactory.getLogger(BosUtils.class);

    private static BosClient client;

    /**
     * 百度BOS文件库名称
     */
    private static String bucketName;

    /**
     * 百度BOS文件链过期时间
     */
    private static Integer expireTime;

    /**
     * 缩略图配置
     */
    private static String imgLayout = "@s_0,w_300,q_60,f_png";

    /**
     * 缩略图配置
     */
    private static String imgLayoutRaw = "@s_0,w_720,q_60,f_png";

    public static void run(String accessKey, String secretKey, String bucketName, String expireTime) {
        BosUtils.bucketName = bucketName;
        BosUtils.expireTime = Integer.parseInt(expireTime);
        BosClientConfiguration config = new BosClientConfiguration();
        // 设置HTTP最大连接数为10
        config.setMaxConnections(100);
        // 设置TCP连接超时为5000毫秒
        config.setConnectionTimeoutInMillis(50000);
        // 设置Socket传输数据超时的时间为2000毫秒
        config.setSocketTimeoutInMillis(30000);
        config.setCredentials(new DefaultBceCredentials(accessKey, secretKey));
        client = new BosClient(config);
        logger.info("BOS 启动!");
    }

    /**
     * 根据百度bosKey获取文件的字节数组
     * @param objectKey
     * @return
     * @throws IOException
     */
    public static byte[] getObjectByte(String objectKey) throws IOException {
        //获取Object,返回结果为BosObject对象
        BosObject object = client.getObject(bucketName, objectKey);
        // 获取ObjectMeta
        ObjectMetadata meta = object.getObjectMetadata();
        //获取Object的输入流
        InputStream objectContent = object.getObjectContent();
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = objectContent.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        objectContent.close();
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    /**
     * 获取Object的URL
     * @param objectKey
     * @return
     */
    public static String generatePresignedUrl(String objectKey, String imgLayout) {
        if (imgLayout != null) {
            objectKey = objectKey + imgLayout;
        }
        URL url = client.generatePresignedUrl(bucketName, objectKey, expireTime);
        //指定用户需要获取的Object所在的Bucket名称、该Object名称、时间戳、URL的有效时长
        return url.toString();
    }

    /**
     * 上传远程图片到bos
     * @param fileUrl
     * @return key
     */
    public static String PutObjectFromURL(String fileUrl) {
        String key = getKey(null);
        try {
            URL url = new URL(fileUrl);
            java.net.URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            client.putObject(bucketName, key, is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return key;
    }

    private static String getKey(String suffix) {
        return CommonUtils.getUUID() + (suffix != null ? "." + suffix : "");
    }

    /**
     * 上传单文件
     * @param ufile
     * @return
     */
    public static String PutObjectFromFile(File ufile) {
        String key = getKey(null);
        PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, ufile);
        // 打印ETag
        System.out.println(putObjectFromFileResponse.getETag());
        return key;
    }

    /**
     * 通过文件流上传单文件
     * @param is     文件流
     * @param suffix 后缀名
     * @return
     */
    public static String PutObjectFromInputStream(InputStream is, String suffix) {
        String key = getKey(suffix);
        PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, is);
        // 打印ETag
        System.out.println(putObjectFromFileResponse.getETag());
        return key;
    }

    /**
       指定原文件名上传
     * @Description //通过文件流上传单文件,附带源文件名
     * @Param [is, suffix, fileName]
     * @return java.lang.String
     **/
    public static String PutObjectFromInputStream(InputStream is, String suffix,String fileName) {
        String key = getKey(suffix);
        // 设置额外属性
        PutObjectResponse putObjectFromFileResponse = null;
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentDisposition("attachment;filename=" + new String(fileName.getBytes(), Charset.forName("ISO-8859-1")));
        putObjectFromFileResponse = client.putObject(bucketName, key, is, meta);
        // 打印ETag
        System.out.println(putObjectFromFileResponse.getETag());
        return key;
    }

    /**
     * 通过二进制串上传单文件
     *
     * @param bytes  二进制串
     * @param suffix 后缀名
     * @return
     */
    public static String putObjectFromByte(byte[] bytes, String suffix) {
        String key = getKey(suffix);
        PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, bytes);
        return key;
    }

    /**
     * 通过bosKeys取文件url列表
     * @param bosKeys(英文逗号分割)
     * @return
     */
    public static List<BosVO> getUrlsByBosKeys(String bosKeys, boolean isImage) {
        if (StringUtils.isBlank(bosKeys)) {
            return new ArrayList<>();
        }
        List<BosVO> urls = new ArrayList<>();
        String[] keys = bosKeys.split(",");
        for (int i = 0; i < keys.length; i++) {
            String url = null;
            BosVO bosUrlVo = new BosVO();
            if (isImage) {
                url = generatePresignedUrl(keys[i], imgLayoutRaw);
                String thumbnailUrl = generatePresignedUrl(keys[i], imgLayout);
                bosUrlVo.setThumbnailUrl(thumbnailUrl);
            } else {
                url = generatePresignedUrl(keys[i], null);
            }
            bosUrlVo.setKey(keys[i]);
            bosUrlVo.setUrl(url);
            urls.add(bosUrlVo);
        }
        return urls;
    }

  /**
   * @Description //获取文件名字和url
   * @Param [list, isImage]
   **/
    public static List<BosVO> getUrlsByBosList(String lists, boolean isImage) {
        if (StringUtils.isBlank(lists)) {
            return new ArrayList<>();
        }
        List<BosVO> urls = new ArrayList<>();
        List<BosFileList> list = new ArrayList<BosFileList>();
        list = JSONObject.parseArray(lists, BosFileList.class);
        for (BosFileList bl : list) {
            String url = null;
            BosVO bosUrlVo = new BosVO();
            if (isImage) {
                url = generatePresignedUrl(bl.getBosKeys(), imgLayoutRaw);
                String thumbnailUrl = generatePresignedUrl(bl.getBosKeys(), imgLayout);
                bosUrlVo.setThumbnailUrl(thumbnailUrl);
            } else {
                url = generatePresignedUrl(bl.getBosKeys(), null);
            }
            bosUrlVo.setKey(bl.getBosKeys());
            bosUrlVo.setName(bl.getBosNames());
            bosUrlVo.setUrl(url);
            urls.add(bosUrlVo);
        }
        return urls;
    }

    /**
     * 通过bosKey取文件url
     *
     * @param bosKey
     * @return
     */
    public static BosVO getUrlByBosKey(String bosKey, boolean isImage) {
        if (bosKey == null) {
            return null;
        }
        String url = null;
        BosVO bosUrlVo = new BosVO();
        if (isImage) {
            url = generatePresignedUrl(bosKey, imgLayoutRaw);
            String thumbnailUrl = generatePresignedUrl(bosKey, imgLayout);
            bosUrlVo.setThumbnailUrl(thumbnailUrl);
        } else {
            url = generatePresignedUrl(bosKey, null);
        }
        bosUrlVo.setUrl(url);
        bosUrlVo.setKey(bosKey);
        return bosUrlVo;
    }

    /**
     * 根据bosKey获取url
     *
     * @param bosKey
     * @return
     */
    public static String getUrlByBosKey(String bosKey) {
        Assert.notNull(bosKey, "bosKey must be not null!");
        return client.generatePresignedUrl(bucketName, bosKey, -1).toString();
    }



    /**
     * 获取指定的bucket中所有的文件key及url输出到bucket-name.txt,配合百度BOS仓库迁移方案
     */
    private static void getBosKeyList(){
        String wsAcc = "";
        String wsSec = "";

        String bucket = "pt-files-test";

        // 初始化一个BosClient
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(wsAcc, wsSec));
        BosClient client = new BosClient(config);

        // 用户可设置每页最多500条记录
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
        listObjectsRequest.withMaxKeys(500);
        boolean isTruncated = true;

        StringBuilder content = new StringBuilder();
        while (isTruncated) {
            ListObjectsResponse listObjectsResponse = client.listObjects(listObjectsRequest);
            isTruncated = listObjectsResponse.isTruncated();
            if (listObjectsResponse.getNextMarker() != null) {
                listObjectsRequest.withMarker(listObjectsResponse.getNextMarker());
            }
            listObjectsResponse.getContents().forEach(obj -> {
                content.append(obj.getKey()+"\t");
                content.append("http://"+bucket+".cdn.bcebos.com/"+obj.getKey()+"\tSTANDARD\r\n");
            });
        }
        try {
            FileWriter fileWriter = new FileWriter("/data/"+bucket+".txt");
            fileWriter.write(content.toString());
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

接口调用

public class FileController {
	//可上传的类型acceptTypes: txt,jpg,jpeg,png,gif,svg,ico,doc,docx,xls,xlsx,ppt,pptx,pdf,flv,mp4,avi,rmvb,apk
    @Value("${file.upload.acceptTypes}")
    String acceptTypes;

    @PostMapping("/file/upload")
    public ResponseVO fileUpload(MultipartFile file) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        String key = "";
        String url = "";
        String thumbnailUrl = "";
        String name = "";
        String suffix = "";
        //上传文件为空抛出异常处理
        if (file == null || file.equals("") || file.getSize() <= 0) {
            return new ResponseVO(400, "上传文件内容为空");
        } else {
            //验证文件格式是否为可接受上传文件
            String originalFilename = file.getOriginalFilename();
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            name = file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."));
            if (acceptTypes.indexOf(suffix) < 0) {
                return new ResponseVO(400, "文件格式不支持");
            } else {
                //调用百度云文件上传工具类返回文件key
                key = BosUtils.PutObjectFromInputStream(file.getInputStream(),suffix.toLowerCase(),originalFilename);
                //获取百度云文件的url
                url = BosUtils.getUrlByBosKey(key);
                thumbnailUrl = BosUtils.getUrlByBosKey(key, true).getThumbnailUrl();
                file.getInputStream().close();
            }
        }
        resultMap.put("key", key);
        resultMap.put("url", url);
        resultMap.put("thumbnailUrl", thumbnailUrl);
        resultMap.put("name", name);
        resultMap.put("type", suffix);
        resultMap.put("size", file.getSize());
        return new ResponseVO(resultMap);
    }

    /**
     * 图片上传(保存本地服务器)
     * @param image
     * @return
     */
    @PostMapping("/file/imageUpload")
    public ResponseVO imageUpload(@RequestParam String image) {
        String facePicPath = "";
        String corpId = "taoding";
        String faceId = CommonUtils.getUUID();
        //截取图片类型:jpg,png,gif
        String imageType = image.substring(image.indexOf("/") + 1, image.indexOf(";"));
        image = image.replace("data:image/" + imageType + ";base64,", "");
        byte[] bytes = CommonUtils.getFromBASE64(image);
        OutputStream out = null;
        String outputPath = facePicPath + File.separator + corpId + File.separator;
        File destFile = new File(outputPath);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        try {
            out = new FileOutputStream(outputPath + File.separator + faceId + "." + imageType);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseVO(outputPath);
    }

    /**
     * 富文本编辑器文件上传
     *
     * @param upload
     * @return
     * @throws IOException
     */
    @PostMapping("/file/ckEditorUpload")
    public Map<String, Object> ueditorUpload(MultipartFile upload) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        String key = "";
        String url = "";
        String name = "";

        //上传文件为空抛出异常处理
        if (upload == null || upload.equals("") || upload.getSize() <= 0) {
            throw new RuntimeException("上传文件为空");
        } else {
            //验证文件格式是否为可接受上传文件
            String suffix = upload.getOriginalFilename().substring(upload.getOriginalFilename().lastIndexOf(".") + 1);
            name = upload.getOriginalFilename();
            if (acceptTypes.indexOf(suffix) < 0) {
                throw new RuntimeException("上传文件格式不支持");
            } else {
                //调用百度云文件上传工具类返回文件key
                key = BosUtils.PutObjectFromInputStream(upload.getInputStream(), suffix,name);
                //获取百度云文件的url
                url = BosUtils.getUrlByBosKey(key);
                upload.getInputStream().close();
            }
        }
        resultMap.put("uploaded", "1");
        resultMap.put("url", url);
        return resultMap;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值