com.qiniu.util.Auth Java Examples

The following examples show how to use com.qiniu.util.Auth. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: QiNiuServiceImpl.java    From DimpleBlog with 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 #7
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 #8
Source File: QiNiuYunMsgSender.java    From WePush with 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 #9
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 #10
Source File: QiniuFileProvider.java    From xiaoyaoji with 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 #11
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 #12
Source File: UserController.java    From MyCommunity with 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 #13
Source File: QiniuStorageManager.java    From sanshanblog with 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 #14
Source File: QiniuUploadServiceImpl.java    From mysiteforme with 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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: QiNiuServiceImpl.java    From yshopmall 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 #25
Source File: QiniuUtils.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 获取私有空间文件
 *
 * @param fileKey
 * @return String
 * @throws Exception
 */
public String getPrivateFile(String fileKey) throws Exception {
    String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
    String url = String.format("%s/%s", fileDomain, encodedFileName);
    Auth auth = Auth.create(accessKey, secretKey);
    long expireInSeconds = 3600;
    //1小时,可以自定义链接过期时间
    return auth.privateDownloadUrl(url, expireInSeconds);
}
 
Example #26
Source File: QiniuController.java    From teaching with Apache License 2.0 5 votes vote down vote up
@AutoLog("获取七牛上传Token")
@ApiOperation(value = "获取七牛覆盖Token", notes = "获取七牛覆盖token")
@RequestMapping("/getTokenByKey")
public Result getQiniuTokenByKey(@RequestParam String key){
    Result result = new Result();
    result.setCode(200);
    Auth auth = Auth.create(QiniuConfig.key, QiniuConfig.secret);
    result.setResult(auth.uploadToken(QiniuConfig.bucket, key, QiniuConfig.expires, null));
    return result;
}
 
Example #27
Source File: QiniuController.java    From teaching with Apache License 2.0 5 votes vote down vote up
@AutoLog("获取七牛上传Token")
@ApiOperation(value = "获取七牛上传Token", notes = "获取七牛上传token")
@RequestMapping("/getToken")
public Result getQiniuToken(){
    Result result = new Result();
    result.setCode(200);
    Auth auth = Auth.create(QiniuConfig.key, QiniuConfig.secret);
    result.setResult(auth.uploadToken(QiniuConfig.bucket, null, QiniuConfig.expires, null));
    return result;
}
 
Example #28
Source File: QiNiuUploadFileTemplateServiceImpl.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public String doSaveFileStore(final MultipartFile file) {
    final Configuration cfg = new Configuration(Zone.autoZone());
    final UploadManager uploadManager = new UploadManager(cfg);
    final Auth auth = Auth.create(ConfigCache.getConfig(Constants.QINIU_ACCESS_KEY), ConfigCache.getConfig(Constants.QINIU_SECRET_KEY));
    final String upToken = auth.uploadToken(ConfigCache.getConfig(Constants.QINIU_BUCKET));
    try {
        final Response response = uploadManager.put(file.getInputStream(), FileUtil.createSingleFileName(file.getOriginalFilename()), upToken, null, null);
        final DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return ConfigCache.getConfig(Constants.QINIU_IMAGE_DOMAIN) + putRet.key;
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #29
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 delete(QiniuContent content, QiniuConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getName() + "." + content.getSuffix());
            qiniuContentService.removeById(content.getId());
        } catch (QiniuException ex) {
            qiniuConfigService.removeById(content.getId());
        }
    }
 
Example #30
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;
}