com.aliyun.oss.OSSClient Java Examples

The following examples show how to use com.aliyun.oss.OSSClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AliyunossProvider.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public AliyunossProvider(String urlprefix,String endpoint, String bucketName, String accessKey, String secretKey,boolean isPrivate) {
	
	Validate.notBlank(endpoint, "[endpoint] not defined");
	Validate.notBlank(bucketName, "[bucketName] not defined");
	Validate.notBlank(accessKey, "[accessKey] not defined");
	Validate.notBlank(secretKey, "[secretKey] not defined");
	Validate.notBlank(urlprefix, "[urlprefix] not defined");
	
	this.accessKeyId = accessKey;
	ossClient = new OSSClient(endpoint, accessKey, secretKey);
	this.bucketName = bucketName;
	this.urlprefix = urlprefix.endsWith("/") ? urlprefix : (urlprefix + "/");
	this.isPrivate = isPrivate;
	this.host = StringUtils.remove(urlprefix,"/").split(":")[1];
	if (!ossClient.doesBucketExist(bucketName)) {
		System.out.println("Creating bucket " + bucketName + "\n");
           ossClient.createBucket(bucketName);
           CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
           createBucketRequest.setCannedACL(isPrivate ? CannedAccessControlList.Private : CannedAccessControlList.PublicRead);
           ossClient.createBucket(createBucketRequest);
	}
}
 
Example #2
Source File: OSSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Start
void start() {
    LOG.info("Start OSSService");

    try {
        String file = plugin.getConfig(FILE_ALIOSS, plugin.getConfig(Config.APP_CONF) + "/alioss.properties");
        if (!new File(file).exists()) { throw new FileNotFoundException("not found " + file); }
        _config.init(file);
        for (String id : _config.getGroupIds()) {
            String endpoint = _config.getConf(id, AliyunField.K_endpoint);
            String accessKeyId = _config.getConf(id, AliyunField.K_accessKeyId);
            String accessKeySecret = _config.getConf(id, AliyunField.K_accessKeySecret);

            ClientConfiguration conf = new ClientConfiguration();
            // TODO config client
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
            clients.put(id, ossClient);
        }
    } catch (Exception e) {
        LOG.error("Start OSSService Failure!" + e.getMessage(), e);
        return;
    }
    LOG.info("Start OSSService Successfully!");
}
 
Example #3
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
    /*//初始化OSSClient

    //上传文件
    String file = "E:\\mnt\\images\\pic\\pider08\\wx_act_img3ca44b69364145cfb6c382a432a3bbd1.jpg";
    File filess = new File(file);
    String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, filess, BACKET_NAME, FOLDER);
    logger.info("上传后的文件MD5数字唯一签名:" + md5key);*/
    for (int j= 1; j < 50; j++) {
        String path = "pic/pider0"+j;
        for (int i = 0; i <200 ; i++) {
            deleteList(ossClient, BACKET_NAME,path);
        }
    }


}
 
Example #4
Source File: AliOssStorage.java    From springboot-learn with MIT License 6 votes vote down vote up
public void delete() {
    if (StringUtils.isAnyBlank(accessKeyId, accessKeySecret, endpoint, bucketName)) {
        throw new IllegalArgumentException("请先设置配置信息");
    }

    //文件所在的目录名
    String fileDir = "image/jpg/";
    //文件名
    String key = "aliU.png";
    String path = fileDir + key;

    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    // 删除文件。
    ossClient.deleteObject(bucketName, path);

    // 关闭OSSClient。
    ossClient.shutdown();
}
 
Example #5
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 创建模拟文件夹
 *
 * @param ossClient  oss连接
 * @param bucketName 存储空间
 * @param folder     模拟文件夹名如"qj_nanjing/"
 * @return 文件夹名
 */
public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
    //文件夹名
    final String keySuffixWithSlash = folder;
    //判断文件夹是否存在,不存在则创建
    if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
        //创建文件夹
        ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
        logger.info("创建文件夹成功");
        //得到文件夹名
        OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
        String fileDir = object.getKey();
        return fileDir;
    }
    return keySuffixWithSlash;
}
 
Example #6
Source File: TestOSSService.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws OSSException, ClientException, IOException {
    OSSClient client = new OSSClient("oss-cn-hangzhou.aliyuncs.com", "", "", "");
    // BucketInfo info = client.getBucketInfo("edrmry");
    boolean exists = client.doesBucketExist("edrmry");
    System.out.println(exists);
    // System.out.println(client.listBuckets().size());
    // client.createBucket("dzh1");
    PutObjectResult r = client.putObject("edrmry", "dzh1.jpg", new FileInputStream("/Users/dzh/Pictures/8.pic.jpg"));
    System.out.println(r.getETag());
    OSSObject o = client.getObject("edrmry", "dzh1");
    InputStream is = o.getObjectContent();

    FileOutputStream fos = new FileOutputStream("/Users/dzh/Pictures/8.pic.2.jpg");
    int len = 0;
    byte[] buf = new byte[32];
    while ((len = is.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
    fos.flush();
    fos.close();
}
 
Example #7
Source File: AliOssAutoConfiguration.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
public OSSClient ossClient() {
	// 创建ClientConfiguration。ClientConfiguration是OSSClient的配置类,可配置代理、连接超时、最大连接数等参数。
	ClientBuilderConfiguration config = new ClientBuilderConfiguration();
	// 设置OSSClient允许打开的最大HTTP连接数,默认为1024个。
	config.setMaxConnections(1024);
	// 设置Socket层传输数据的超时时间,默认为50000毫秒。
	config.setSocketTimeout(50000);
	// 设置建立连接的超时时间,默认为50000毫秒。
	config.setConnectionTimeout(50000);
	// 设置从连接池中获取连接的超时时间(单位:毫秒),默认不超时。
	config.setConnectionRequestTimeout(1000);
	// 设置连接空闲超时时间。超时则关闭连接,默认为60000毫秒。
	config.setIdleConnectionTime(60000);
	// 设置失败请求重试次数,默认为3次。
	config.setMaxErrorRetry(5);
	// 配置协议
	config.setProtocol(ossProperties.getAliOss()
		.getHttps() ? Protocol.HTTPS : Protocol.HTTP);

	return (OSSClient) new OSSClientBuilder().build(ossProperties.getAliOss()
		.getEndpoint(), ossProperties.getAliOss()
		.getAccessKey(), ossProperties.getAliOss()
		.getSecretKey(), config);
}
 
Example #8
Source File: OSSUploadTest.java    From cms with Apache License 2.0 6 votes vote down vote up
@Test
	public void upload(){
		OSSClient client=OSSClientFactory.create();
		
		String bucketName="b-cdn";
		String path="/opt/001.jpg";
		PutObjectResult result=client.putObject(bucketName, "cms"+path, new File(path));
		JSONObject json = JSONObject.fromObject(result);
		
		System.out.println(json.toString());
		
		// 列举bucket
//		List<Bucket> buckets = client.listBuckets();
//		for (Bucket bucket : buckets) {
//		    System.out.println(" - " + bucket.getName());
//		}
		
		
		client.shutdown();
	}
 
Example #9
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, InputStream inputStream) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, inputStream).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example #10
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(String objectName) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        ossClient.deleteObject(bucketName, objectName);
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
}
 
Example #11
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, byte[] bytes) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(bytes)).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example #12
Source File: ApiBootOssOverrideService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 创建bucket存储
 *
 * @param bucketName 存储名称
 */
public void createBucket(String bucketName) {
    OSSClient ossClient = getOssClient();
    Bucket bucket = ossClient.createBucket(bucketName);
    logger.info("新创建存储空间名称:{}", bucket.getName());
    logger.info("新创建存储空间所属人:{}", bucket.getOwner().getDisplayName());
    closeOssClient(ossClient);
}
 
Example #13
Source File: OSSFather.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
public static OSSClient getOSSClient() {
    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
    if (ossClient.doesBucketExist(bucketName_user)) {
        logger.debug("您已经创建Bucket:" + bucketName_user + "。");
    } else {
        logger.debug("您的Bucket不存在,创建Bucket:" + bucketName_user + "。");
        ossClient.createBucket(bucketName_user);
    }
    BucketInfo info = ossClient.getBucketInfo(bucketName_user);
    logger.debug("Bucket " + bucketName_user + "的信息如下:");
    logger.debug("\t数据中心:" + info.getBucket().getLocation());
    logger.debug("\t创建时间:" + info.getBucket().getCreationDate());
    logger.debug("\t用户标志:" + info.getBucket().getOwner());
    return ossClient;
}
 
Example #14
Source File: OSSClientFactory.java    From cms with Apache License 2.0 5 votes vote down vote up
public static OSSClient create() {
	if(client==null){
		AuthOSSClient authOSSClient = new AuthOSSClient();
		client = authOSSClient.create();
	}
	return client;
}
 
Example #15
Source File: ImgServiceImpl.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
public void delectOSS(Keys key, String fileName) {
    String endpoint = key.getEndpoint();
    String accessKeyId = key.getAccessKey();
    String accessKeySecret = key.getAccessSecret();
    String bucketName = key.getBucketname();
    String objectName = fileName;
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    ossClient.deleteObject(bucketName, objectName);
    ossClient.shutdown();
}
 
Example #16
Source File: OSSImageupload.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Integer Initialize(Keys k) {
    int ret = -1;
    if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
            && k.getBucketname()!=null && k.getRequestAddress()!=null ) {
        if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
                && !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
            ossClient = new OSSClient(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret());
            key = k;
            ret=1;
        }
    }
    return ret;
}
 
Example #17
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String copyFile(String fromKey, String toKey) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.copyObject(os.getBucket(), fromKey, os.getBucket(), toKey);
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
}
 
Example #18
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, String localFile) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File(localFile)).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example #19
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void download(String objectName, String localFile) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        ossClient.getObject(new GetObjectRequest(bucketName, objectName).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)), new File(localFile));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
}
 
Example #20
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String inputStreamUpload(InputStream inputStream, String key, MultipartFile file) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.putObject(os.getBucket(), key, inputStream);
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
}
 
Example #21
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * get oss client instance
 *
 * @return {@link OSSClient}
 * @throws ApiBootObjectStorageException ApiBoot Oss Exception
 */
protected OSSClient getOssClient() throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    } catch (Exception e) {
        throw new ApiBootObjectStorageException("获取OssClient对象异常.", e);
    }
}
 
Example #22
Source File: StorageAutoConfiguration.java    From cola-cloud with MIT License 5 votes vote down vote up
/**
 * 根据配置文件自动装配阿里云SSO存储组件
 *
 * @return AliyunFileStorage.class
 */
@Bean
@ConditionalOnProperty(prefix = "cola.storage", name = "type", havingValue = "aliyun" )
@ConditionalOnMissingBean(FileStorage.class)
@Order(0)
public AliyunFileStorage aliyunFileStorage() {
    OSSClient ossClient = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    AliyunFileStorage aliyunFileUpload = new AliyunFileStorage(ossClient);
    aliyunFileUpload.setBucketName(ossProperties.getBucketName());
    return aliyunFileUpload;
}
 
Example #23
Source File: AliyunUtil.java    From roncoo-education with MIT License 5 votes vote down vote up
/**
 * 文件存储入OSS
 * 
 * @param bucketName
 * @param key
 * @param inputStream
 */
private static PutObjectResult putObjectForFile(String endpoint, String keyId, String keySecret, String bucketName, String key, InputStream inputStream, String fileName) {
	OSSClient ossClient = getOssClient(endpoint, keyId, keySecret);
	ObjectMetadata meta = new ObjectMetadata();
	if (StringUtils.isNotBlank(fileName)) {
		meta.setContentDisposition("attachment;filename={}".replace("{}", fileName));
		meta.setObjectAcl(CannedAccessControlList.Private);
	}
	return ossClient.putObject(bucketName, key, inputStream, meta);
}
 
Example #24
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 创建存储空间
 *
 * @param ossClient  OSS连接
 * @param bucketName 存储空间
 * @return
 */
public static String createBucketName(OSSClient ossClient, String bucketName) {
    //存储空间
    final String bucketNames = bucketName;
    if (!ossClient.doesBucketExist(bucketName)) {
        //创建存储空间
        Bucket bucket = ossClient.createBucket(bucketName);
        logger.info("创建存储空间成功");
        return bucket.getName();
    }
    return bucketNames;
}
 
Example #25
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取储空间buckName的文件列表
 *
 * @param ossClient  oss对象
 * @param bucketName 存储空间
 */
public static void deleteList(OSSClient ossClient, String bucketName, String folder) {
    ObjectListing listObjects = ossClient.listObjects(bucketName);
    // 遍历所有Object

    for (OSSObjectSummary objectSummary : listObjects.getObjectSummaries()) {
        String key = objectSummary.getKey();
        logger.info("key=" + key);
        Random random = new Random();
        boolean nextBoolean =random.nextBoolean();
        if (nextBoolean) {
            deleteFile(ossClient, bucketName, folder, key);
        }
    }
}
 
Example #26
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static void close(OSSClient ossClient) {
    if (ossClient != null) {
        try {
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
 
Example #27
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 上传阿里云OSS
 *
 * @param ossPath
 * @param file
 * @return
 */
public static String upLoadFileOSS(File file,String ossPath) {
    String BACKET_NAME = "xmf-article-img";
    logger.info("开始上传OSS");
    OSSClient ossClient = null;
    String md5key = null;
    try {
        if (file == null) {
            return md5key;
        }
        String path = ossPath;
        String name = path+"/"+file.getName();
        ossClient = AliyunOSSClientUtil.getOSSClient();
        AliyunOSSClientUtil.createFolder(ossClient, BACKET_NAME, ossPath);
        md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, BACKET_NAME, ossPath + "/");
        logger.info("上传oss成功:" + name);
    } catch (Exception e) {
        AliyunOSSClientUtil.close(ossClient);
        logger.info("获取连接异常:" + e.getMessage());
        e.printStackTrace();
    }
    if (ossClient == null) {
        logger.info("获取连接为空");
    }
    AliyunOSSClientUtil.close(ossClient);
    return md5key;
}
 
Example #28
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 同步本地文件到阿里云OSS
 *
 * @param path
 * @param file
 * @return
 */
public static boolean uploadsync(String path, File file) {

    boolean enable = JPressOptions.getAsBool(KEY_ENABLE);

    if (!enable || StrUtil.isBlank(path)) {
        return false;
    }

    path = removeFileSeparator(path);
    path = path.replace('\\', '/');

    String ossBucketName = JPressOptions.get(KEY_BUCKETNAME);
    OSSClient ossClient = createOSSClient();

    try {
        ossClient.putObject(ossBucketName, path, file);
        boolean success = ossClient.doesObjectExist(ossBucketName, path);
        if (!success) {
            LogKit.error("aliyun oss upload error! path:" + path + "\nfile:" + file);
        }
        return success;

    } catch (Throwable e) {
        log.error("aliyun oss upload error!!!", e);
        return false;
    } finally {
        ossClient.shutdown();
    }
}
 
Example #29
Source File: OssJwtKeyConfiguration.java    From daming with Apache License 2.0 5 votes vote down vote up
@Bean(name = "smsVerificationJwtSigningKeyBytesLoader")
public OssKeyLoader ossJwtKeyLoader(@Qualifier("daming.jwt.key.ossClient") OSSClient ossClient) {
    OssKeyLoader loader = new OssKeyLoader(ossClient);
    loader.setBucketName(bucketName);
    loader.setObjectName(objectName);
    return loader;
}
 
Example #30
Source File: OssUploadServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
    ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
    try {
        OSSClient ossClient = new OSSClient(uploadInfo.getOssEndpoint(),uploadInfo.getOssKeyId(), uploadInfo.getOssKeySecret());
        InputStream inputStream = classPathResource .getInputStream();
        ossClient.putObject(uploadInfo.getOssBucketName(), "test.jpg", inputStream, null);
        ossClient.shutdown();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}