Java Code Examples for com.qiniu.util.Auth

The following examples show how to use com.qiniu.util.Auth. 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: MyCommunity   Author: UHungLin   File: UserController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/setting", method = RequestMethod.GET)
public String getSettingPage(Model model) {
    // 上传文件名称
    String fileName = GetGenerateUUID.generateUUID();
    // 设置响应信息
    StringMap policy = new StringMap();
    policy.put("returnBody", JSONUtil.getJSONString(0));
    // 生成上传凭证
    Auth auth = Auth.create(accessKey, secretKey);
    String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

    model.addAttribute("uploadToken", uploadToken);
    model.addAttribute("fileName", fileName);

    return "/site/setting";
}
 
Example #2
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 #3
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 #4
Source Project: WePush   Author: rememberber   File: QiNiuYunMsgSender.java    License: MIT License 6 votes vote down vote up
/**
 * 获取七牛云短信发送客户端
 *
 * @return SmsSingleSender
 */
private static SmsManager getSmsManager() {
    if (smsManager == null) {
        synchronized (QiNiuYunMsgSender.class) {
            if (smsManager == null) {
                // 设置需要操作的账号的AK和SK
                String qiniuAccessKey = App.config.getQiniuAccessKey();
                String qiniuSecretKey = App.config.getQiniuSecretKey();
                Auth auth = Auth.create(qiniuAccessKey, qiniuSecretKey);

                smsManager = new SmsManager(auth);
            }
        }
    }
    return smsManager;
}
 
Example #5
Source Project: BigDataPlatform   Author: KangU4   File: QiniuUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String qiniuBase64Upload(String data64){

        String key = renamePic(".png");
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        //服务端http://up-z2.qiniup.com
        String url = "http://up-z2.qiniup.com/putb64/-1/key/"+ UrlSafeBase64.encodeToString(key);
        RequestBody rb = RequestBody.create(null, data64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return origin+key;
    }
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source Project: xiaoyaoji   Author: Bin-mario   File: QiniuFileProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 上传
 *
 * @param path  文件路径
 * @param bytes 文件流
 * @return 上传后的文件夹名称
 */
@Override
public String upload(String path, byte[] bytes) throws IOException {
    Auth auth = Auth.create(ConfigUtils.getQiniuAccessKey(), ConfigUtils.getQiniuSecretKey());
    UploadManager uploadManager = new UploadManager();
    try {
        String token = auth.uploadToken(ConfigUtils.getBucketURL(), path, 3600, new StringMap().put("insertOnly", 0));
        Response res = uploadManager.put(bytes, path, token);
        String result = res.bodyString();
        logger.debug("qiniuUpload:" + result);
        if (result.contains("\"key\"")) {
            return path;
        }
        throw new IOException(result);
    } catch (QiniuException e) {
        Response r = e.response;
        throw new IOException(r.bodyString());
    }
}
 
Example #12
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 #13
Source Project: DimpleBlog   Author: DimpleFeng   File: QiNiuServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getDownloadUrl(Long id) {
    QiNiuConfig qiNiuConfig = getQiNiuConfig();
    if (!qiNiuConfig.check()) {
        throw new CustomException("七牛云配置信息不完整,请先填写七牛云配置信息");
    }
    QiNiuContent qiNiuContent = qiNiuContentMapper.selectContentById(id);
    if (Objects.isNull(qiNiuConfig)) {
        throw new CustomException("对应文件不存在,建议同步数据后再试");
    }
    if ("公开".equals(qiNiuConfig.getType())) {
        return qiNiuContent.getUrl();
    } else {
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        // 1小时,可以自定义链接过期时间
        long expireInSeconds = 3600;
        return auth.privateDownloadUrl(qiNiuContent.getUrl(), expireInSeconds);
    }
}
 
Example #14
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 #15
Source Project: sanshanblog   Author: SanShanYouJiu   File: QiniuStorageManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传Ueditor的文件
 * @param inputStream
 * @param key
 * @param type
 * @param metedata
 */
public void ueditorUpload(InputStream inputStream, String key, String type, Object metedata) {
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(ueditor_bucket);
    try {
        Response response = uploadManager.put(inputStream, 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.error(r.toString());
        try {
            log.error(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
}
 
Example #16
Source Project: mysiteforme   Author: wangl1989   File: QiniuUploadServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
    ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
    try {
        Auth auth = Auth.create(uploadInfo.getQiniuAccessKey(), uploadInfo.getQiniuSecretKey());
        String authstr =  auth.uploadToken(uploadInfo.getQiniuBucketName());
        InputStream inputStream = classPathResource .getInputStream();
        Response response = getUploadManager().put(inputStream,"test.jpg",authstr,null,null);
        if(response.isOK()){
            return true;
        }else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #17
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 #18
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 #19
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Cacheable
public String download(QiniuContent content, QiniuConfig config) {
    String finalUrl;
    String type = "公开";
    if (type.equals(content.getType())) {
        finalUrl = content.getUrl();
    } else {
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        // 1小时,可以自定义链接过期时间
        long expireInSeconds = 3600;
        finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
    }
    return finalUrl;
}
 
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 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 #21
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 #22
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuFileManage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String pathUpload(String filePath, String key) {

    OssSetting os = getOssSetting();
    Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
    String upToken = auth.uploadToken(os.getBucket());
    try {
        Response response = getUploadManager(getConfiguration(os.getZone())).put(filePath, key, upToken);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        throw new SkException("上传文件出错,请检查七牛云配置," + r.toString());
    }
}
 
Example #23
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuFileManage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String inputStreamUpload(InputStream inputStream, String key, MultipartFile file) {

    OssSetting os = getOssSetting();
    Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
    String upToken = auth.uploadToken(os.getBucket());
    try {
        Response response = getUploadManager(getConfiguration(os.getZone())).put(inputStream, key, upToken, null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        throw new SkException("上传文件出错,请检查七牛云配置," + r.toString());
    }
}
 
Example #24
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuFileManage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String renameFile(String fromKey, String toKey) {

    OssSetting os = getOssSetting();
    Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
    try {
        bucketManager.move(os.getBucket(), fromKey, os.getBucket(), toKey);
        return os.getHttp() + os.getEndpoint() + "/" + toKey;
    } catch (QiniuException ex) {
        throw new SkException("重命名文件失败," + ex.response.toString());
    }
}
 
Example #25
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuFileManage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String copyFile(String fromKey, String toKey) {

    OssSetting os = getOssSetting();
    Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
    try {
        bucketManager.copy(os.getBucket(), fromKey, os.getBucket(), toKey);
        return os.getHttp() + os.getEndpoint() + "/" + toKey;
    } catch (QiniuException ex) {
        throw new SkException("复制文件失败," + ex.response.toString());
    }
}
 
Example #26
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuFileManage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteFile(String key) {

    OssSetting os = getOssSetting();
    Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
    try {
        bucketManager.delete(os.getBucket(), key);
    } catch (QiniuException ex) {
        throw new SkException("删除文件失败," + ex.response.toString());
    }
}
 
Example #27
Source Project: smart-admin   Author: 1024-lab   File: FileServiceQiNiuYun.java    License: MIT License 5 votes vote down vote up
/**
 * 获取下载路径
 */
public String getDownloadUrl(String key) {
    OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
    String domainOfBucket = ossConfig.getEndpoint();
    String finalUrl = "";
    try {
        String encodedFileName = URLEncoder.encode(key, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
    } catch (Exception e) {
        log.error("QINIU download ERROR : {}", e);
    }
    return finalUrl;
}
 
Example #28
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 #29
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 #30
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);
	}
}