com.qiniu.storage.Configuration Java Examples

The following examples show how to use com.qiniu.storage.Configuration. 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: AttachmentServiceImpl.java    From blog-sharon with 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 #2
Source File: QiniuFileUtil.java    From mysiteforme with 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 #3
Source File: QiniuFileUtil.java    From mysiteforme with 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 #4
Source File: QiNiuStorage.java    From springboot-learn with 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 #5
Source File: QiniuApiClient.java    From OneBlog with 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 #6
Source File: QiniuOssClientTest.java    From markdown-image-kit with 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 #7
Source File: QiniuOssClient.java    From markdown-image-kit with 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 File: FileUploadImpl.java    From uexam-mysql with 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 #9
Source File: QiNiuUtil.java    From javabase with 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 #10
Source File: AttachmentServiceImpl.java    From stone with 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 #11
Source File: QiniuUtil.java    From BigDataPlatform with 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 #12
Source File: QiniuProvider.java    From jeesuite-libs with 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 #13
Source File: AttachmentServiceImpl.java    From SENS with 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 #14
Source File: FileServiceQiNiuYun.java    From smart-admin with 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 #15
Source File: QiniuServiceImpl.java    From jframe with 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 #16
Source File: FileUploadImpl.java    From uexam with 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 #17
Source File: QiniuStorageImpl.java    From mblog with 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 File: QiniuOssFileHandler.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void delete(String key) {
    Assert.notNull(key, "File key must not be blank");

    Region region = optionService.getQiniuRegion();

    String accessKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString();
    String secretKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString();
    String bucket = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString();

    // Create configuration
    Configuration configuration = new Configuration(region);

    // Create auth
    Auth auth = Auth.create(accessKey, secretKey);

    BucketManager bucketManager = new BucketManager(auth, configuration);

    try {
        Response response = bucketManager.delete(bucket, key);
        if (!response.isOK()) {
            log.warn("附件 " + key + " 从七牛云删除失败");
        }
    } catch (QiniuException e) {
        log.error("Qiniu oss error response: [{}]", e.response);
        throw new FileOperationException("附件 " + key + " 从七牛云删除失败", e);
    }
}
 
Example #19
Source File: QiniuOssUtil.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
public static String upload(FileInputStream file, String fileName) {
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    // 其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    try {
        Auth auth = Auth.create(properies.getOss().getQiniu().getAccessKey(), properies.getOss().getQiniu().getSecretKey());
        String upToken = auth.uploadToken(properies.getOss().getQiniu().getBucket());
        try {
            Response response = uploadManager.put(file, fileName, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            return properies.getOss().getQiniu().getPath() + "/" + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.error(r.toString());
            try {
                logger.error(r.bodyString());
            } catch (QiniuException ignore) {

            }
        }
    } catch (Exception e) {
        logger.error("error", e);
    }
    return null;
}
 
Example #20
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
/***
 * 普通上传图片
 * @param file
 * @return
 * @throws QiniuException
 * @throws IOException
 */
public static String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException {
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	String fileName = "", extName = "", filePath = "";
	if (null != file && !file.isEmpty()) {
		extName = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf("."));
		fileName = UUID.randomUUID() + extName;
		UploadManager uploadManager = new UploadManager(config);
		Auth auth = Auth.create(qiniuAccess, qiniuKey);
		String token = auth.uploadToken(bucketName);
		byte[] data = file.getBytes();
		QETag tag = new QETag();
		String hash = tag.calcETag(file);
		Rescource rescource = new Rescource();
		EntityWrapper<RestResponse> wrapper = new EntityWrapper<>();
		wrapper.eq("hash",hash);
		rescource = rescource.selectOne(wrapper);
		if( rescource!= null){
			return rescource.getWebUrl();
		}
		Response r = uploadManager.put(data, fileName, token);
		if (r.isOK()) {
			filePath = path + fileName;
			rescource = new Rescource();
			rescource.setFileName(fileName);
			rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.getSize()/1024)+"kb");
			rescource.setHash(hash);
			rescource.setFileType(StringUtils.isBlank(extName)?"unknown":extName);
			rescource.setWebUrl(filePath);
			rescource.setSource("qiniu");
			rescource.insert();
		}
	}
	return filePath;
}
 
Example #21
Source File: FileService.java    From ml-blog with MIT License 5 votes vote down vote up
/**
 * 创建七牛云相关组件
 */
private void createQiniuComponent() {
    Configuration cfg = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(commonMap.get("qn_accessKey").toString(), commonMap.get("qn_secretKey").toString());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    String upToken = auth.uploadToken(commonMap.get("qn_bucket").toString());
    commonMap.put("uploadManager",uploadManager);
    commonMap.put("bucketManager",bucketManager);
    commonMap.put("upToken",upToken);
}
 
Example #22
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
/***
 * 删除已经上传的图片
 * @param imgPath
 */
public static void deleteQiniuP(String imgPath) {
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	Auth auth = Auth.create(qiniuAccess, qiniuKey);
	BucketManager bucketManager = new BucketManager(auth,config);
	imgPath = imgPath.replace(path, "");
	try {
		bucketManager.delete(bucketName, imgPath);
	} catch (QiniuException e) {
		e.printStackTrace();
	}
}
 
Example #23
Source File: QiniuProvider.java    From azeroth with Apache License 2.0 5 votes vote down vote up
public QiniuProvider(String urlprefix, String bucketName, String accessKey, String secretKey) {
    this.urlprefix = urlprefix.endsWith(DIR_SPLITER) ? urlprefix : urlprefix + DIR_SPLITER;
    this.bucketName = bucketName;
    auth = Auth.create(accessKey, secretKey);

    Zone z = Zone.autoZone();
    Configuration c = new Configuration(z);
    uploadManager = new UploadManager(c);
    bucketManager = new BucketManager(auth, c);
}
 
Example #24
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
/***
 * 上传本地图片
 * @param src
 * @return
 */
public static String uploadLocalImg(String src) throws IOException, NoSuchAlgorithmException{
	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);
	File file = new File(src);
	if(!file.exists()){
		throw new MyException("本地文件不存在");
	}
	QETag tag = new QETag();
	String hash = tag.calcETag(file);
	Rescource rescource = new Rescource();
	EntityWrapper<RestResponse> wrapper = new EntityWrapper<>();
	wrapper.eq("hash",hash);
	rescource = rescource.selectOne(wrapper);
	if( rescource!= null){
		return rescource.getWebUrl();
	}
	String filePath="",
			extName = "",
	name = UUID.randomUUID().toString();
	extName = file.getName().substring(
			file.getName().lastIndexOf("."));
	Response response = uploadManager.put(file,name,token);
	if(response.isOK()){
		filePath = path + name;
		rescource = new Rescource();
		rescource.setFileName(name);
		rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.length()/1024)+"kb");
		rescource.setHash(hash);
		rescource.setFileType(StringUtils.isBlank(extName)?"unknown":extName);
		rescource.setWebUrl(filePath);
		rescource.setSource("qiniu");
		rescource.insert();
	}
	return filePath;
}
 
Example #25
Source File: QiniuApiClient.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 上传图片
 *
 * @param is       图片流
 * @param imageUrl 图片路径
 * @return 上传后的路径
 */
@Override
public VirtualFile uploadImg(InputStream is, String imageUrl) {
    this.check();

    String key = FileUtil.generateTempFileName(imageUrl);
    this.createNewFileName(key, this.pathPrefix);
    Date startTime = new Date();
    //Zone.zone0:华东
    //Zone.zone1:华北
    //Zone.zone2:华南
    //Zone.zoneNa0:北美
    Configuration cfg = new Configuration(Region.autoRegion());
    UploadManager uploadManager = new UploadManager(cfg);
    try {
        Auth auth = Auth.create(this.accessKey, this.secretKey);
        String upToken = auth.uploadToken(this.bucket);
        Response response = uploadManager.put(is, this.newFileName, upToken, null, null);

        //解析上传成功的结果
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

        return new VirtualFile()
                .setOriginalFileName(key)
                .setSuffix(this.suffix)
                .setUploadStartTime(startTime)
                .setUploadEndTime(new Date())
                .setFilePath(putRet.key)
                .setFileHash(putRet.hash)
                .setFullFilePath(this.path + putRet.key);
    } catch (QiniuException ex) {
        throw new QiniuApiException("[" + this.storageType + "]文件上传失败:" + ex.error());
    }
}
 
Example #26
Source File: QNUploader.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
public UploadInfo upload(String qq, File file, String ak, String sk,
        String bucket, Zone zone) throws Exception {
        
    // 默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = String.format("%s/%s", qq, file.getName());
    AuthInfo authInfo = getToken(qq, ak, sk, bucket, key);
    System.out.println(authInfo);
    if (authInfo.limit > 0 && file.length() > authInfo.limit) {
        throw new RuntimeException("今日上传流量不足,剩余流量:" + authInfo.limit);
    }
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(
            zone == null ? Zone.autoZone() : zone);
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    com.qiniu.http.Response response = uploadManager
            .put(file.getAbsolutePath(), key, authInfo.token);
    if (!response.isOK()) {
        throw new RuntimeException(
                response.error + "(code=" + response.statusCode + ")");
    }
    // 解析上传成功的结果
    UploadInfo putRet = new Gson().fromJson(response.bodyString(),
            UploadInfo.class);
    if (authInfo.domain != null && !authInfo.domain.isEmpty()) {
        putRet.domain = authInfo.domain;
    }
    if (authInfo.limit > 0) {
        callback(qq, putRet);
    }
    return putRet;
}
 
Example #27
Source File: QiNiuServiceImpl.java    From sk-admin with 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 #28
Source File: QiNiuUtil.java    From javabase with Apache License 2.0 5 votes vote down vote up
public void test(){
        String key="1539702607173729.mp4";
        String saveJpgEntry = String.format("%s:test.jpg", bucketName);
        String persistentOpfs = String.format("vframe/jpg/offset/1/w/500/h/500|saveas/%s", UrlSafeBase64.encodeToString(saveJpgEntry));

        //数据处理队列名称,必须
        String persistentPipeline = "mps-pipe1"+System.currentTimeMillis();
//数据处理完成结果通知地址
        String persistentNotifyUrl = "http://api.example.com/qiniu/pfop/notify";
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
//构建持久化数据处理对象
        OperationManager operationManager = new OperationManager(auth, cfg);
        try {
            String persistentId = operationManager.pfop(bucketName, key, persistentOpfs, persistentPipeline, persistentNotifyUrl, true);
            //可以根据该 persistentId 查询任务处理进度
            System.out.println(persistentId);
            OperationStatus operationStatus = operationManager.prefop(persistentId);

            System.out.println("operationStatus");
            //解析 operationStatus 的结果
        } catch (Exception e) {
            log.error("",e);
        }

    }
 
Example #29
Source File: QiniuStorageImpl.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
    String accessKey = options.getValue(oss_key);
    String secretKey = options.getValue(oss_secret);
    String domain = options.getValue(oss_domain);
    String bucket = options.getValue(oss_bucket);
    String src = options.getValue(oss_src);

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

    if (StringUtils.isNotBlank(src)) {
        if (src.startsWith("/")) {
            src = src.substring(1);
        }

        if (!src.endsWith("/")) {
            src = src + "/";
        }
    } else {
        src = "";
    }

    String key = UpYunUtils.md5(bytes);
    String path = src + key + FileKit.getSuffix(pathAndFileName);

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket, path);

    UploadManager uploadManager = new UploadManager(configuration);
    Response response = uploadManager.put(bytes, path, upToken);

    if (!response.isOK()) {
        throw new MtonsException(response.bodyString());
    }
    return domain.trim() + "/" + path;
}
 
Example #30
Source File: QiniuOSSTest.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    File file = new File("F:/data/a_2.jpg");
    byte[] bytes = ImageUtils.screenshot(file, 360, 200);
    final String key = "/static" + UpYunUtils.md5(bytes) + ".jpg";

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);

    final Auth auth = Auth.create(accessKey, secretKey);
    final String upToken = auth.uploadToken(bucket, key);
    try {
        final UploadManager uploadManager = new UploadManager(configuration);
        final Response response = uploadManager.put(bytes, key, upToken);
        System.out.println(response.bodyString());
        System.out.println(response.isOK());
    } catch (QiniuException e) {
        final Response r = e.response;
        System.err.println(r.toString());
        try {
            System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
    String filePath = domain.trim()+ key + ".jpg";
    System.out.println(filePath);
}