Java Code Examples for com.qiniu.storage.Configuration

The following examples show how to use com.qiniu.storage.Configuration. These examples are extracted from open source projects. 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 Project: uexam   Author: alvis-u   File: FileUploadImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream, long size, String extName) {
    QnConfig qnConfig = systemConfig.getQn();
    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qnConfig.getAccessKey(), qnConfig.getSecretKey());
    String upToken = auth.uploadToken(qnConfig.getBucket());
    try {
        Response response = uploadManager.put(inputStream, null, upToken, null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return qnConfig.getUrl() + "/" + putRet.key;
    } catch (QiniuException ex) {
        logger.error(ex.getMessage(), ex);
    }
    return null;
}
 
Example #2
Source Project: smart-admin   Author: 1024-lab   File: FileServiceQiNiuYun.java    License: MIT License 6 votes vote down vote up
@Override
public ResponseDTO<String> getFileUrl(String path) {
    OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
    try {
        if (! ossConfig.toString().equals(accessConfig)) {
            //accessKeyId 发生变动自动重新创建新的UploadManager
            ossClient = new UploadManager(new Configuration());
            token = Auth.create(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()).
                uploadToken(ossConfig.getBucketName());
            accessConfig = ossConfig.toString();
        }
        String encodedFileName = URLEncoder.encode(path, "utf-8");
        String domainOfBucket = ossConfig.getEndpoint();
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = ossConfig.getAccessKeyId();
        String secretKey = ossConfig.getAccessKeySecret();
        Auth auth = Auth.create(accessKey, secretKey);
        //1小时,可以自定义链接过期时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return ResponseDTO.succData(finalUrl);
    } catch (Exception e) {
        log.error("QINIU getFileUrl ERROR : {}", e);
    }
    return ResponseDTO.wrap(FileResponseCodeConst.URL_ERROR);
}
 
Example #3
Source Project: SENS   Author: saysky   File: AttachmentServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 七牛云删除附件
 *
 * @param key key
 * @return boolean
 */
@Override
public boolean deleteQiNiuAttachment(String key) {
    boolean flag = true;
    final Configuration cfg = new Configuration(Zone.zone0());
    final String accessKey = SensConst.OPTIONS.get("qiniu_access_key");
    final String secretKey = SensConst.OPTIONS.get("qiniu_secret_key");
    final String bucket = SensConst.OPTIONS.get("qiniu_bucket");
    if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(bucket)) {
        return false;
    }
    final Auth auth = Auth.create(accessKey, secretKey);
    final BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
        bucketManager.delete(bucket, key);
    } catch (QiniuException ex) {
        System.err.println(ex.code());
        System.err.println(ex.response.toString());
        flag = false;
    }
    return flag;
}
 
Example #4
Source Project: BigDataPlatform   Author: KangU4   File: QiniuUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 文件流上传
 * @param file
 * @param key 文件名
 * @return
 */
public static String qiniuInputStreamUpload(FileInputStream file, String key){

    //构造一个带指定Zone对象的配置类 zone2华南
    Configuration cfg = new Configuration(Zone.zone2());

    UploadManager uploadManager = new UploadManager(cfg);

    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);

    try {
        Response response = uploadManager.put(file,key,upToken,null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return origin+putRet.key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.warn(r.toString());
        try {
            return r.bodyString();
        } catch (QiniuException e) {
            throw new XmallUploadException(e.toString());
        }
    }
}
 
Example #5
Source Project: stone   Author: Alension   File: AttachmentServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 七牛云删除附件
 *
 * @param key key
 * @return boolean
 */
@Override
public boolean deleteQiNiuAttachment(String key) {
    boolean flag = true;
    final Configuration cfg = new Configuration(Zone.zone0());
    final String accessKey = HaloConst.OPTIONS.get("qiniu_access_key");
    final String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key");
    final String bucket = HaloConst.OPTIONS.get("qiniu_bucket");
    if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(bucket)) {
        return false;
    }
    final Auth auth = Auth.create(accessKey, secretKey);
    final BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
        bucketManager.delete(bucket, key);
    } catch (QiniuException ex) {
        System.err.println(ex.code());
        System.err.println(ex.response.toString());
        flag = false;
    }
    return flag;
}
 
Example #6
Source Project: uexam-mysql   Author: alvis-u   File: FileUploadImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream, long size, String extName) {
    QnConfig qnConfig = systemConfig.getQn();
    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qnConfig.getAccessKey(), qnConfig.getSecretKey());
    String upToken = auth.uploadToken(qnConfig.getBucket());
    try {
        Response response = uploadManager.put(inputStream, null, upToken, null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return qnConfig.getUrl() + "/" + putRet.key;
    } catch (QiniuException ex) {
        logger.error(ex.getMessage(), ex);
    }
    return null;
}
 
Example #7
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClient.java    License: MIT License 6 votes vote down vote up
/**
 * 如果是第一次使用, ossClient == null
 */
private static void init() {
    QiniuOssState qiniuOssState = MikPersistenComponent.getInstance().getState().getQiniuOssState();
    domain = qiniuOssState.getEndpoint();
    String accessKey = qiniuOssState.getAccessKey();
    String secretKey = DES.decrypt(qiniuOssState.getAccessSecretKey(), MikState.QINIU);
    String bucketName = qiniuOssState.getBucketName();

    Optional<ZoneEnum> zone = EnumsUtils.getEnumObject(ZoneEnum.class, e -> e.getIndex() == qiniuOssState.getZoneIndex());
    try {
        Configuration cfg = new Configuration(zone.orElse(ZoneEnum.EAST_CHINA).zone);
        ossClient = new UploadManager(cfg);
        buildToken(Auth.create(accessKey, secretKey), bucketName);
    } catch (Exception ignored) {
    }
}
 
Example #8
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClientTest.java    License: MIT License 6 votes vote down vote up
public static String upload(byte[] uploadBytes, String preFix, String bucket, String accessKey, String secretKey) {
    Configuration cfg = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(cfg);
    String key = "";
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    log.info("token: " + upToken);
    try {
        Response response = uploadManager.put(uploadBytes, preFix + "-" + System.currentTimeMillis(), upToken);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        key = putRet.key;
        log.info("key: " + putRet.key);
        log.info("hash: " + putRet.hash);
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.info(r.toString());
        try {
            log.info(r.bodyString());
        } catch (QiniuException ignored) {
        }
    }
    return key;
}
 
Example #9
Source Project: springboot-learn   Author: fujiangwei   File: QiNiuStorage.java    License: MIT License 6 votes vote down vote up
public void deleteFile() {
    if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
        throw new IllegalArgumentException("请先设置配置信息");
    }

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

    String path = StringUtils.remove(fileDir + key, domain.trim());

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);
    Auth auth = Auth.create(accessKey, secretKey);

    BucketManager bucketManager = new BucketManager(auth, configuration);
    try {
        bucketManager.delete(bucket, path);
    } catch (QiniuException e) {
        Response r = e.response;
        System.out.println(e.response.getInfo());
    }
}
 
Example #10
Source Project: blog-sharon   Author: qinxuewu   File: AttachmentServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 七牛云删除附件
 *
 * @param key key
 * @return boolean
 */
@Override
public boolean deleteQiNiuAttachment(String key) {
    boolean flag = true;
    Configuration cfg = new Configuration(Zone.zone0());
    String accessKey = HaloConst.OPTIONS.get("qiniu_access_key");
    String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key");
    String bucket = HaloConst.OPTIONS.get("qiniu_bucket");
    if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(bucket)) {
        return false;
    }
    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
        bucketManager.delete(bucket, key);
    } catch (QiniuException ex) {
        System.err.println(ex.code());
        System.err.println(ex.response.toString());
        flag = false;
    }
    return flag;
}
 
Example #11
Source Project: mysiteforme   Author: wangl1989   File: QiniuFileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * 上传网络图片
 * @param src
 * @return
 */
public static String uploadImageSrc(String src){
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	Auth auth = Auth.create(qiniuAccess, qiniuKey);
	BucketManager bucketManager = new BucketManager(auth, config);
	String fileName = UUID.randomUUID().toString(),filePath="";
	try {
		FetchRet fetchRet = bucketManager.fetch(src, bucketName);
		filePath = path + fetchRet.key;
		Rescource rescource = new Rescource();
		rescource.setFileName(fetchRet.key);
		rescource.setFileSize(new java.text.DecimalFormat("#.##").format(fetchRet.fsize/1024)+"kb");
		rescource.setHash(fetchRet.hash);
		rescource.setFileType(fetchRet.mimeType);
		rescource.setWebUrl(filePath);
		rescource.setSource("qiniu");
		rescource.insert();
	} catch (QiniuException e) {
		filePath = src;
		e.printStackTrace();
	}
	return filePath;
}
 
Example #12
Source Project: mysiteforme   Author: wangl1989   File: QiniuFileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传base64位的图片
 * @param base64
 * @return
 */
public static String uploadBase64(String base64,String name) {
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	UploadManager uploadManager = new UploadManager(config);
	Auth auth = Auth.create(qiniuAccess, qiniuKey);
	String token = auth.uploadToken(bucketName),filePath;

	byte[] data = Base64.decodeBase64(base64);
	try {
		uploadManager.put(data,name,token);
	} catch (IOException e) {
		e.printStackTrace();
	}
	filePath = path+name;
	return filePath;
}
 
Example #13
Source Project: OneBlog   Author: zhangyd-c   File: QiniuApiClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 删除七牛空间图片方法
 *
 * @param key 七牛空间中文件名称
 */
@Override
public boolean removeFile(String key) {
    this.check();

    if (StringUtils.isNullOrEmpty(key)) {
        throw new QiniuApiException("[" + this.storageType + "]删除文件失败:文件key为空");
    }
    Auth auth = Auth.create(this.accessKey, this.secretKey);
    Configuration config = new Configuration(Region.autoRegion());
    BucketManager bucketManager = new BucketManager(auth, config);
    try {
        Response re = bucketManager.delete(this.bucket, key);
        return re.isOK();
    } catch (QiniuException e) {
        Response r = e.response;
        throw new QiniuApiException("[" + this.storageType + "]删除文件发生异常:" + r.toString());
    }
}
 
Example #14
Source Project: javabase   Author: ggj2010   File: QiNiuUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Configuration cfg = new Configuration(Zone.zone0());
    cfg.connectTimeout=5000;
    cfg.readTimeout=5000;
    cfg.writeTimeout=2000;
    auth = Auth.create(accessKey, secretKey);
    uploadManager = new UploadManager(cfg);
    // 实例化一个BucketManager对象
    bucketManager = new BucketManager(auth, cfg);

    new Thread() {
        public void run() {
            deleteBlockingDequeImage();
        }
    }.start();
}
 
Example #15
Source Project: jeesuite-libs   Author: vakinge   File: QiniuProvider.java    License: Apache License 2.0 6 votes vote down vote up
public QiniuProvider(String urlprefix, String bucketName, String accessKey, String secretKey,boolean isPrivate) {
	
	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.urlprefix = urlprefix.endsWith(DIR_SPLITER) ? urlprefix : urlprefix + DIR_SPLITER;
	this.bucketName = bucketName;
	auth = Auth.create(accessKey, secretKey);

	Zone region = Zone.autoZone();
	Configuration c = new Configuration(region);
	uploadManager = new UploadManager(c);
	bucketManager = new BucketManager(auth,c);
	
	this.isPrivate = isPrivate;
	this.host = StringUtils.remove(urlprefix,"/").split(":")[1];
}
 
Example #16
Source Project: jframe   Author: dzh   File: QiniuServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Start
void start() {
    try {
        CONFIG.init(PLUGIN.getConfig(FILE_CONF));
        if ("".equals(CONFIG.getConf(null,
                QiniuConfig.AK))) { throw new ServiceException("Error in configuration , lost parameter -> " + QiniuConfig.AK); }
        if ("".equals(CONFIG.getConf(null,
                QiniuConfig.SK))) { throw new ServiceException("Error in configuration , lost parameter -> " + QiniuConfig.SK); }

        LOG.info("QiniuService {}", CONFIG);
        AUTH = Auth.create(CONFIG.getConf(null, QiniuConfig.AK), CONFIG.getConf(null, QiniuConfig.SK));
        BUCKET = new BucketManager(AUTH, new Configuration());

        LOG.info("QiniuService start successfully!");
    } catch (Exception e) {
        LOG.error("QiniuService start error -> {}", e.getMessage());
    }
}
 
Example #17
Source Project: mblog   Author: langhsu   File: QiniuStorageImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void deleteFile(String storePath) {
    String accessKey = options.getValue(oss_key);
    String secretKey = options.getValue(oss_secret);
    String domain = options.getValue(oss_domain);
    String bucket = options.getValue(oss_bucket);

    if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
        throw new MtonsException("请先在后台设置阿里云配置信息");
    }

    String path = StringUtils.remove(storePath, domain.trim());

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);
    Auth auth = Auth.create(accessKey, secretKey);

    BucketManager bucketManager = new BucketManager(auth, configuration);
    try {
        bucketManager.delete(bucket, path);
    } catch (QiniuException e) {
        Response r = e.response;
        log.error(e.getMessage(), r.toString());
    }
}
 
Example #18
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
    FileUtils.checkSize(maxSize, file.getSize());
    if (qiniuConfig.getId() == null) {
        throw new SkException("请先添加相应配置,再操作");
    }
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
    String upToken = auth.uploadToken(qiniuConfig.getBucket());
    try {
        String key = file.getOriginalFilename();
        if (qiniuContentDao.findByKey(key) != null) {
            key = QiNiuUtil.getKey(key);
        }
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        //解析上传成功的结果

        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        //存入数据库
        QiniuContent qiniuContent = new QiniuContent();
        qiniuContent.setSuffix(FileUtils.getExtensionName(putRet.key));
        qiniuContent.setBucket(qiniuConfig.getBucket());
        qiniuContent.setType(qiniuConfig.getType());
        qiniuContent.setKey(FileUtils.getFileNameNoEx(putRet.key));
        qiniuContent.setUrl(qiniuConfig.getHost() + "/" + putRet.key);
        qiniuContent.setSize(FileUtils.getSize(Integer.parseInt(file.getSize() + "")));
        return qiniuContentDao.save(qiniuContent);
    } catch (Exception e) {
        throw new SkException(e.getMessage());
    }
}
 
Example #19
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void delete(QiniuContent content, QiniuConfig config) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
    Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
        bucketManager.delete(content.getBucket(), content.getKey() + "." + content.getSuffix());
        qiniuContentDao.delete(content);
    } catch (QiniuException ex) {
        qiniuContentDao.delete(content);
    }
}
 
Example #20
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void synchronize(QiniuConfig config) {
    if (config.getId() == null) {
        throw new SkException("请先添加相应配置,再操作");
    }
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
    Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    //文件名前缀
    String prefix = "";
    //每次迭代的长度限制,最大1000,推荐值 1000
    int limit = 1000;
    //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
    String delimiter = "";
    //列举空间文件列表
    BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
    while (fileListIterator.hasNext()) {
        //处理获取的file list结果
        QiniuContent qiniuContent;
        FileInfo[] items = fileListIterator.next();
        for (FileInfo item : items) {
            if (qiniuContentDao.findByKey(FileUtils.getFileNameNoEx(item.key)) == null) {
                qiniuContent = new QiniuContent();
                qiniuContent.setSize(FileUtils.getSize(Integer.parseInt(item.fsize + "")));
                qiniuContent.setSuffix(FileUtils.getExtensionName(item.key));
                qiniuContent.setKey(FileUtils.getFileNameNoEx(item.key));
                qiniuContent.setType(config.getType());
                qiniuContent.setBucket(config.getBucket());
                qiniuContent.setUrl(config.getHost() + "/" + item.key);
                qiniuContentDao.save(qiniuContent);
            }
        }
    }
}
 
Example #21
Source Project: smart-admin   Author: 1024-lab   File: FileServiceQiNiuYun.java    License: MIT License 5 votes vote down vote up
@Override
public ResponseDTO<UploadVO> fileUpload(MultipartFile multipartFile, String path) {
    OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
    try {
        InputStream inputStream = new ByteArrayInputStream(multipartFile.getBytes());
        if (! ossConfig.toString().equals(accessConfig)) {
            //accessKeyId 发生变动自动重新创建新的UploadManager
            ossClient = new UploadManager(new Configuration());
            token = Auth.create(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()).
                uploadToken(ossConfig.getBucketName());
            accessConfig = ossConfig.toString();
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String ossPath = path + "/" + uuid;
        String fileName = multipartFile.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
        String mime = this.getContentType(fileExt);
        Response res = ossClient.put(inputStream, ossPath, token, null, mime);
        if (! res.isOK()) {
            log.error("QINIU fileUpload ERROR : {}", res.toString());
            return ResponseDTO.wrap(FileResponseCodeConst.UPLOAD_ERROR);
        }
        UploadVO localUploadVO = new UploadVO();
        localUploadVO.setUrl(this.getFileUrl(ossPath).getData());
        localUploadVO.setFileName(fileName);
        localUploadVO.setFilePath(ossPath);
        localUploadVO.setFileSize(multipartFile.getSize());
        return ResponseDTO.succData(localUploadVO);
    } catch (Exception e) {
        log.error("QINIU fileUpload ERROR : {}", e);
    }
    return ResponseDTO.wrap(FileResponseCodeConst.UPLOAD_ERROR);
}
 
Example #22
Source Project: BigDataPlatform   Author: KangU4   File: QiniuUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String qiniuUpload(String filePath){

        //构造一个带指定Zone对象的配置类 zone2华南
        Configuration cfg = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager(cfg);

        String localFilePath = filePath;
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return origin+putRet.key;
        }catch(QiniuException ex){
            Response r = ex.response;
            log.warn(r.toString());
            try {
                return r.bodyString();
            } catch (QiniuException e) {
                throw new XmallUploadException(e.toString());
            }
        }
    }
 
Example #23
Source Project: mogu_blog_v2   Author: moxi624   File: QiNiuRestApi.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    //zong2() 代表华南地区
    Configuration cfg = new Configuration(Zone.zone2());

    UploadManager uploadManager = new UploadManager(cfg);

    //AccessKey的值
    String accessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";

    //SecretKey的值
    String secretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";

    //存储空间名
    String bucket = "XXXXXXXXXXX";

    //上传图片路径
    String localFilePath = "D:\\1582507567527.png";

    //在七牛云中图片的命名
    String key = "1582507567527.png";
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    try {
        Response response = uploadManager.put(localFilePath, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
    } catch (QiniuException ex) {
        Response r = ex.response;
        System.err.println(r.toString());
        try {
            System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
}
 
Example #24
Source Project: spring-microservice-exam   Author: wells2333   File: QiNiuUtil.java    License: MIT License 5 votes vote down vote up
public QiNiuUtil() {
	qiNiuConfig = SpringContextHolder.getApplicationContext().getBean(QiNiuConfig.class);
	if (StringUtils.isNotBlank(qiNiuConfig.getAccessKey()) && StringUtils.isNotBlank(qiNiuConfig.getSecretKey())) {
		instance = new QiNiuUtil();
		instance.auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
		Configuration config = new Configuration(Region.region2());
		instance.uploadManager = new UploadManager(config);
		instance.bucketManager = new BucketManager(instance.auth, config);
	}
}
 
Example #25
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClient.java    License: MIT License 5 votes vote down vote up
/**
 * test 按钮点击事件后请求, 成功后保留 client, paste 或者 右键 上传时使用
 *
 * @param inputStream the input stream
 * @param fileName    the file name
 * @param bucketName  the bucketName name
 * @param accessKey   the access key
 * @param secretKey   the secret key
 * @param endpoint    the endpoint
 * @param zoneIndex   the zone index
 * @return the string
 */
@NotNull
@Contract(pure = true)
public String upload(InputStream inputStream,
                     String fileName,
                     String bucketName,
                     String accessKey,
                     String secretKey,
                     String endpoint,
                     int zoneIndex) {


    QiniuOssClient qiniuOssClient = QiniuOssClient.getInstance();
    Optional<ZoneEnum> zone = EnumsUtils.getEnumObject(ZoneEnum.class, e -> e.getIndex() == zoneIndex);
    Configuration cfg = new Configuration(zone.orElse(ZoneEnum.EAST_CHINA).zone);
    UploadManager ossClient = new UploadManager(cfg);
    Auth auth = Auth.create(accessKey, secretKey);
    // 重新生成 token
    QiniuOssClient.buildToken(auth, bucketName);

    qiniuOssClient.setDomain(endpoint);

    String url = qiniuOssClient.upload(ossClient, inputStream, fileName);

    if (StringUtils.isNotBlank(url)) {
        int hashcode = bucketName.hashCode() +
                       accessKey.hashCode() +
                       secretKey.hashCode() +
                       endpoint.hashCode() +
                       zoneIndex;
        OssState.saveStatus(MikPersistenComponent.getInstance().getState().getQiniuOssState(),
                            hashcode,
                            MikState.OLD_HASH_KEY);
        qiniuOssClient.setOssClient(ossClient);
    }
    return url;
}
 
Example #26
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClientTest.java    License: MIT License 5 votes vote down vote up
public static String upload(InputStream inputStream, String bucket, String preFix, String accessKey, String secretKey) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释

    UploadManager uploadManager = new UploadManager(cfg);

    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = null;

    byte[] uploadBytes = "hello qiniu cloud".getBytes(StandardCharsets.UTF_8);
    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);

    try {
        Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info(putRet.key);
        log.info(putRet.hash);
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.info(r.toString());
        try {
            log.info(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }

    return "";
}
 
Example #27
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClientTest.java    License: MIT License 5 votes vote down vote up
public static String upload(File file, String bucket, String accessKey, String secretKey, String endpoint) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释

    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = "test.png";

    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    BucketManager bucketManager = new BucketManager(auth, cfg);

    try {
        Response response = uploadManager.put(file, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info(putRet.key);
        log.info(putRet.hash);

        FileInfo fileInfo = bucketManager.stat(bucket, key);
        System.out.println(fileInfo.hash);
        System.out.println(fileInfo.fsize);
        System.out.println(fileInfo.mimeType);
        System.out.println(fileInfo.putTime);
        return endpoint + key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.info(r.toString());
        try {
            log.info(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
    return "";
}
 
Example #28
Source Project: yshopmall   Author: guchengwuyue   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(QiniuContent content, QiniuConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getName() + "." + content.getSuffix());
            qiniuContentService.removeById(content.getId());
        } catch (QiniuException ex) {
            qiniuConfigService.removeById(content.getId());
        }
    }
 
Example #29
Source Project: yshopmall   Author: guchengwuyue   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void synchronize(QiniuConfig config) {
        if(config.getId() == null){
            throw new BadRequestException("请先添加相应配置,再操作");
        }
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制,最大1000,推荐值 1000
        int limit = 1000;
        //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            QiniuContent qiniuContent;
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                if(qiniuContentService.getOne(new QueryWrapper<QiniuContent>().eq("name",FileUtil.getFileNameNoEx(item.key)))
                        == null){
                    qiniuContent = new QiniuContent();
                    qiniuContent.setSize(FileUtil.getSize(Integer.parseInt(item.fsize+"")));
                    qiniuContent.setSuffix(FileUtil.getExtensionName(item.key));
                    qiniuContent.setName(FileUtil.getFileNameNoEx(item.key));
                    qiniuContent.setType(config.getType());
                    qiniuContent.setBucket(config.getBucket());
                    qiniuContent.setUrl(config.getHost()+"/"+item.key);
                    qiniuContentService.save(qiniuContent);
                }
            }
        }
    }
 
Example #30
Source Project: plumemo   Author: byteblogs168   File: QiNiuUploadFileTemplateServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String doSaveFileStore(final MultipartFile file) {
    final Configuration cfg = new Configuration(Zone.autoZone());
    final UploadManager uploadManager = new UploadManager(cfg);
    final Auth auth = Auth.create(ConfigCache.getConfig(Constants.QINIU_ACCESS_KEY), ConfigCache.getConfig(Constants.QINIU_SECRET_KEY));
    final String upToken = auth.uploadToken(ConfigCache.getConfig(Constants.QINIU_BUCKET));
    try {
        final Response response = uploadManager.put(file.getInputStream(), FileUtil.createSingleFileName(file.getOriginalFilename()), upToken, null, null);
        final DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return ConfigCache.getConfig(Constants.QINIU_IMAGE_DOMAIN) + putRet.key;
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return "";
}