com.qiniu.common.Zone Java Examples

The following examples show how to use com.qiniu.common.Zone. 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 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 #2
Source File: OptionServiceImplTest.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
private void getQiniuZoneTest(Zone actualZone, Option option) {
        QiniuOssProperties zoneProperty = QiniuOssProperties.OSS_ZONE;

        // Given
//        given(optionRepository.findByKey(zoneProperty.getValue())).willReturn(Optional.ofNullable(option));
        Map<String, Object> optionMap = new HashMap<>(1);
        optionMap.put(zoneProperty.getValue(), Optional.ofNullable(option).map(Option::getValue).orElse(null));
        given(cacheStore.getAny(OptionService.OPTIONS_KEY, Map.class)).willReturn(Optional.of(optionMap));

        // When
        Zone zone = optionService.getQnYunZone();

        // Then
        then(cacheStore).should().getAny(OptionService.OPTIONS_KEY, Map.class);

        assertNotNull(zone);
        assertThat(zone.getRegion(), equalTo(actualZone.getRegion()));
    }
 
Example #3
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 #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: 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 #6
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 #7
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 #8
Source File: QNUploaderTest.java    From SmartIM with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpload2() {
    QNUploader uploader = new QNUploader();
    String ak = "";
    String sk = "";
    String bucket = "";
    File f = new File("C:\\Users\\Jamling\\Desktop\\a.txt");
    Zone zone = null;
    try {
        UploadInfo info = uploader.upload("157250921", f, ak, sk, bucket,
                zone);
        System.out.println(info);
    } catch (Exception e) {
        e.printStackTrace();
        //fail(e.getMessage());
    }
}
 
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: FileUploadConfig.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据配置文件选择机房
 */
@Bean
public com.qiniu.storage.Configuration qiniuConfig() {
    Zone zone = null;
    if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) {
        zone = Zone.huabei();
    } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) {
        zone = Zone.huadong();
    } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) {
        zone = Zone.huanan();
    } else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) {
        zone = Zone.beimei();
    } else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) {
        zone = Zone.xinjiapo();
    }
    return new com.qiniu.storage.Configuration(zone);
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: Configuration.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public String rsHost(String ak, String bucket) {
    ZoneReqInfo zoneReqInfo = new ZoneReqInfo(ak, bucket);
    if (zone == null) {
        zone = Zone.autoZone();
    }
    return useHttpsDomains ? zone.getRsHttps(zoneReqInfo)
            : zone.getRsHttp(zoneReqInfo);
}
 
Example #16
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 #17
Source File: Configuration.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public String ioHost(String ak, String bucket) {
    ZoneReqInfo zoneReqInfo = new ZoneReqInfo(ak, bucket);
    if (zone == null) {
        zone = Zone.autoZone();
    }
    return useHttpsDomains ? zone.getIovipHttps(zoneReqInfo)
            : zone.getIovipHttp(zoneReqInfo);
}
 
Example #18
Source File: Configuration.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public String apiHost(String ak, String bucket) {
    ZoneReqInfo zoneReqInfo = new ZoneReqInfo(ak, bucket);
    if (zone == null) {
        zone = Zone.autoZone();
    }

    return useHttpsDomains ? zone.getApiHttps(zoneReqInfo)
            : zone.getApiHttp(zoneReqInfo);
}
 
Example #19
Source File: QiniuCloudService.java    From my-site with Apache License 2.0 5 votes vote down vote up
public String upload(MultipartFile file, String fileName) {

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response response = null;

            response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example #20
Source File: OptionServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Zone getQnYunZone() {
    return getByProperty(QiniuOssProperties.OSS_ZONE).map(qiniuZone -> {

        Zone zone;
        switch (qiniuZone.toString()) {
            case "z0":
                zone = Zone.zone0();
                break;
            case "z1":
                zone = Zone.zone1();
                break;
            case "z2":
                zone = Zone.zone2();
                break;
            case "na0":
                zone = Zone.zoneNa0();
                break;
            case "as0":
                zone = Zone.zoneAs0();
                break;
            default:
                // Default is detecting zone automatically
                zone = Zone.autoZone();
        }
        return zone;

    }).orElseGet(Zone::autoZone);
}
 
Example #21
Source File: QiniuUtil.java    From BigDataPlatform with 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 #22
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 #23
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 #24
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);
}
 
Example #25
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 #26
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 #27
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 #28
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 #29
Source File: QNUploaderTest.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpload() {
    QNUploader uploader = new QNUploader();
    try {
        
        String ak = "";
        String sk = "";
        String bucket = "temp";
        File f = new File("pom.xml");
        Zone zone = null;
        UploadInfo info = uploader.upload("testqq", f, ak, sk, bucket,
                zone);
        System.out.println(info);
        assertEquals("testqq/pom.xml", info.key);
        assertEquals("temp", info.bucket);
        assertEquals(f.length(), info.fsize);
        assertEquals("http://temp.ieclipse.cn/testqq/pom.xml",
                info.getUrl("http://temp.ieclipse.cn", false));
                
        AuthInfo auth = uploader.getToken("testqq", "", "", "",
                "pom.xml");
        System.out.println(auth);
        assertNotNull(auth);
        assertNotNull(auth.token);
        assertEquals("http://temp.ieclipse.cn", auth.domain);
        assertEquals(1, auth.days);
        assertTrue((8 << 20) >= auth.limit);
        
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example #30
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);
}