Java Code Examples for com.qiniu.util.Auth#create()

The following examples show how to use com.qiniu.util.Auth#create() . 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 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 2
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 3
Source File: QiniuUtil.java    From BigDataPlatform with 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 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: 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 6
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 7
Source File: QiNiuServiceImpl.java    From sk-admin with 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 8
Source File: QiniuStorageManager.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
/**
 *
 根据名字删除文件
 */
public void ueditorDeleteFile(String filename) {
    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
        bucketManager.delete(ueditor_bucket,filename);
    } catch (QiniuException e) {
        //删除失败
        log.error(e.getMessage());
        e.printStackTrace();
    }
}
 
Example 9
Source File: QiNiuServiceImpl.java    From yshopmall with 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 10
Source File: QiniuUtil.java    From newblog with Apache License 2.0 5 votes vote down vote up
public static String getToken(String bucket) {
    System.out.println("qiniuyun");
    String access_key = "QN3U7hRV4WYTmNSPJLVGCfuthzwN2MsDnPojtaZ4";
    String secret_key = "4qqIC6qDc4-KNfSqbG3WOvgSEN8mZx5zEDOsAdo8";
    if (access_key != null && secret_key != null) {
        Auth auth = Auth.create(access_key, secret_key);
        String token = auth.uploadToken(bucket);
        return token;
    } else {
        return null;
    }

}
 
Example 11
Source File: QiNiuServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
    FileUtil.checkSize(maxSize, file.getSize());
    if(qiniuConfig.getId() == null){
        throw new BadRequestException("请先添加相应配置,再操作");
    }
    // 构造一个带指定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(qiniuContentRepository.findByKey(key) != null) {
            key = QiNiuUtil.getKey(key);
        }
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        //解析上传成功的结果

        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        QiniuContent content = qiniuContentRepository.findByKey(FileUtil.getFileNameNoEx(putRet.key));
        if(content == null){
            //存入数据库
            QiniuContent qiniuContent = new QiniuContent();
            qiniuContent.setSuffix(FileUtil.getExtensionName(putRet.key));
            qiniuContent.setBucket(qiniuConfig.getBucket());
            qiniuContent.setType(qiniuConfig.getType());
            qiniuContent.setKey(FileUtil.getFileNameNoEx(putRet.key));
            qiniuContent.setUrl(qiniuConfig.getHost()+"/"+putRet.key);
            qiniuContent.setSize(FileUtil.getSize(Integer.parseInt(file.getSize()+"")));
            return qiniuContentRepository.save(qiniuContent);
        }
        return content;
    } catch (Exception e) {
       throw new BadRequestException(e.getMessage());
    }
}
 
Example 12
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 13
Source File: QiNiuServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
@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());
        qiniuContentRepository.delete(content);
    } catch (QiniuException ex) {
        qiniuContentRepository.delete(content);
    }
}
 
Example 14
Source File: QiNiuServiceImpl.java    From DimpleBlog with Apache License 2.0 4 votes vote down vote up
@Override
@Transactional
public int synchronize() {
    QiNiuConfig qiNiuConfig = getQiNiuConfig();
    if (!qiNiuConfig.check()) {
        throw new CustomException("七牛云配置信息不完整,请先填写七牛云配置信息");
    }
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtils.getRegion(qiNiuConfig.getZone()));
    Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    //文件名前缀
    String prefix = "";
    //每次迭代的长度限制,最大1000,推荐值 1000
    int limit = 1000;
    //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
    String delimiter = "";
    //列举空间文件列表
    BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(qiNiuConfig.getBucket(), prefix, limit, delimiter);
    int count = 0;
    while (fileListIterator.hasNext()) {
        //处理获取的file list结果
        QiNiuContent qiNiuContent;
        //删除所有数据
        qiNiuContentMapper.clearContent();
        FileInfo[] items = fileListIterator.next();
        if (Objects.nonNull(items)) {
            String username = SecurityUtils.getUsername();
            for (FileInfo item : items) {
                qiNiuContent = new QiNiuContent();
                qiNiuContent.setSize(FileUtils.getSizeString(Integer.parseInt(item.fsize + "")));
                qiNiuContent.setSuffix(FileUtils.getExtensionName(item.key));
                qiNiuContent.setName(FileUtils.getFileNameNoExtension(item.key));
                qiNiuContent.setType(qiNiuConfig.getType());
                qiNiuContent.setBucket(qiNiuConfig.getBucket());
                qiNiuContent.setUrl("http://" + qiNiuConfig.getHost() + "/" + item.key);
                qiNiuContent.setCreateBy(username);
                qiNiuContent.setCreateTime(convertUnixTime(item.putTime + ""));
                count += qiNiuContentMapper.insertContent(qiNiuContent);
            }

        }
    }
    return count;
}
 
Example 15
Source File: QiNiuUtils.java    From ClipIt with MIT License 4 votes vote down vote up
private static String getToken() {
    Auth auth = Auth.create(accessKey, secretKey);
    return auth.uploadToken(bucket);
}
 
Example 16
Source File: FileUploadConfig.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 认证信息实例
 * @return
 */
@Bean
public Auth auth() {
    return Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
}
 
Example 17
Source File: QiniuOssFileHandler.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");

    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();
    String protocol = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_DOMAIN).toString();
    String source = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_SOURCE, String.class, "");
    String styleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");

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

    // Create auth
    Auth auth = Auth.create(accessKey, secretKey);
    // Build put plicy
    StringMap putPolicy = new StringMap();
    putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"size\":$(fsize),\"width\":$(imageInfo.width),\"height\":$(imageInfo.height)}");
    // Get upload token
    String uploadToken = auth.uploadToken(bucket, null, 60 * 60, putPolicy);

    // Create temp path
    Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket);

    StringBuilder basePath = new StringBuilder(protocol)
        .append(domain)
        .append(URL_SEPARATOR);

    try {
        String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String timestamp = String.valueOf(System.currentTimeMillis());
        StringBuilder upFilePath = new StringBuilder();
        if (StringUtils.isNotEmpty(source)) {
            upFilePath.append(source)
                .append(URL_SEPARATOR);
        }
        upFilePath.append(basename)
            .append("_")
            .append(timestamp)
            .append(".")
            .append(extension);

        // Get file recorder for temp directory
        FileRecorder fileRecorder = new FileRecorder(tmpPath.toFile());
        // Get upload manager
        UploadManager uploadManager = new UploadManager(configuration, fileRecorder);
        // Put the file
        Response response = uploadManager.put(file.getInputStream(), upFilePath.toString(), uploadToken, null, null);

        if (log.isDebugEnabled()) {
            log.debug("Qiniu oss response: [{}]", response.toString());
            log.debug("Qiniu oss response body: [{}]", response.bodyString());
        }

        // Convert response
        PutSet putSet = JsonUtils.jsonToObject(response.bodyString(), PutSet.class);

        // Get file full path
        String filePath = StringUtils.join(basePath.toString(), upFilePath.toString());

        // Build upload result
        UploadResult result = new UploadResult();
        result.setFilename(basename);
        result.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule);
        result.setKey(upFilePath.toString());
        result.setSuffix(extension);
        result.setWidth(putSet.getWidth());
        result.setHeight(putSet.getHeight());
        result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        result.setSize(file.getSize());

        if (isImageType(result.getMediaType())) {
            if (ImageUtils.EXTENSION_ICO.equals(extension)) {
                result.setThumbPath(filePath);
            } else {
                result.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule);
            }
        }

        return result;
    } catch (IOException e) {
        if (e instanceof QiniuException) {
            log.error("Qiniu oss error response: [{}]", ((QiniuException) e).response);
        }

        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到七牛云失败", e);
    }
}
 
Example 18
Source File: QiniuConfigure.java    From cms with Apache License 2.0 4 votes vote down vote up
@Bean
public Auth getAuth() {
    Auth auth = Auth.create(accessKey, secretKey);
    return auth;
}
 
Example 19
Source File: QiniuUploader.java    From poster-generater with MIT License 4 votes vote down vote up
@Autowired
public void setAuth() {
    this.auth = Auth.create(config.getAccess(), config.getSecret());
}
 
Example 20
Source File: QiniuConfiguration.java    From blade-tool with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Bean
public Auth auth() {
	return Auth.create(ossProperties.getAccessKey(), ossProperties.getSecretKey());
}