com.qiniu.common.QiniuException Java Examples

The following examples show how to use com.qiniu.common.QiniuException. 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: QiniuServiceImpl.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
@Override
public String uploadStream(InputStream is, String fileName) {
    try {

        String key = qiniuProperties.getBucket() + '/' + DateUtils.format(LocalDateTime.now(), DateUtils.NORM_DATE_PATTERN) + "/" + fileName;
        Response response = uploadManager.put(is, key, this.getToken(), null, null);
        if (response.isOK()) {
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        }

    } catch (QiniuException e) {
        throw new RuntimeException("上传文件失败");
    }
    return null;
}
 
Example #2
Source File: QiniuUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public static void putFile(String bucket, String key, File file) {
        try {
//            Response res = uploadManager.put(filePath, key, getToken(bucket));
            Response res = uploadManager.put(file, key, getToken(bucket));
            if (!res.isOK()) {
                log.error("Upload to qiniu failed;File path: " + file.getPath() + ";Error: " + res.error);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            Response r = e.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                log.error(e1.getMessage());
            }
        }
    }
 
Example #3
Source File: QiniuUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public static void putFile(String bucket, String key, String filePath) {
    try {
        Response res = uploadManager.put(filePath, key, getToken(bucket));
        if (!res.isOK()) {
            log.error("Upload to qiniu failed;File path: " + filePath + ";Error: " + res.error);
        }
    } catch (QiniuException e) {
        e.printStackTrace();
        Response r = e.response;
        log.error(r.toString());
        try {
            log.error(r.bodyString());
        } catch (QiniuException e1) {
            log.error(e1.getMessage());
        }
    }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: QiniuUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public static void putFileBytes(String bucket, String key, byte[] bytes) {
        try {
//            Response res = uploadManager.put(filePath, key, getToken(bucket));
            Response res = uploadManager.put(bytes, key, getToken(bucket));
            if (!res.isOK()) {
                log.error("Upload to qiniu failed;File path: " + ";Error: " + res.error);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            Response r = e.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException e1) {
                log.error(e1.getMessage());
            }
        }
    }
 
Example #8
Source File: Tool.java    From EasyHousing with MIT License 6 votes vote down vote up
public void upload(String FilePath, String newPhotoName) throws IOException{
	try {  
		//BucketManager bucketMgr = new BucketManager(auth, cfg);
		//bucketMgr.delete(bucketname, newPhotoName);
     Response res = uploadManager.put(FilePath, newPhotoName, getUpToken());  
     System.out.println(res.isOK());
     System.out.println(res.bodyString());
 } catch (QiniuException e) {  
        Response r = e.response;  
        System.out.println(r.toString());  
        try {  
          System.out.println(r.bodyString());  
        } catch (QiniuException e1) {  
            //ignore  
        }
    }         
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: QiniuProvider.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public String upload(UploadObject object) {
	String fileName = object.getFileName();
	if(StringUtils.isNotBlank(object.getCatalog())){
		fileName = object.getCatalog().concat(FilePathHelper.DIR_SPLITER).concat(fileName);
	}
	try {
		Response res = null;
		String upToken = getUpToken(object.getMetadata());
		if(object.getFile() != null){
			res = uploadManager.put(object.getFile(), fileName, upToken);
		}else if(object.getBytes() != null){
			res = uploadManager.put(object.getBytes(), fileName, upToken);
		}else if(object.getInputStream() != null){
			res = uploadManager.put(object.getInputStream(), fileName, upToken, null, object.getMimeType());
		}else if(StringUtils.isNotBlank(object.getUrl())){
			return bucketManager.fetch(object.getUrl(), bucketName, fileName).key;
		}else{
			throw new IllegalArgumentException("upload object is NULL");
		}
		return processUploadResponse(res);
	} catch (QiniuException e) {
		processUploadException(fileName, e);
	}
	return null;
}
 
Example #14
Source File: AttachFileServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String uploadFile(byte[] bytes,String originalName) throws QiniuException {
	String extName = FileUtil.extName(originalName);
	String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;


	AttachFile attachFile = new AttachFile();
	attachFile.setFilePath(fileName);
	attachFile.setFileSize(bytes.length);
	attachFile.setFileType(extName);
	attachFile.setUploadTime(new Date());
	attachFileMapper.insert(attachFile);

	String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
    Response response = uploadManager.put(bytes, fileName, upToken);
    Json.parseObject(response.bodyString(),  DefaultPutRet.class);
	return fileName;
}
 
Example #15
Source File: QiniuCloud.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 删除文件
 * 
 * @param key
 * @return
 */
protected boolean delete(String key) {
	Assert.notNull(auth, "云存储账户未配置");
	BucketManager bucketManager = new BucketManager(auth, CONFIGURATION);
	Response resp;
	try {
		resp = bucketManager.delete(this.bucketName, key);
		if (resp.isOK()) {
			return true;
		} else {
			throw new RebuildException("删除文件失败 : " + this.bucketName + " < " + key + " : " + resp.bodyString());
		}
	} catch (QiniuException e) {
		throw new RebuildException("删除文件失败 : " + this.bucketName + " < " + key, e);
	}
}
 
Example #16
Source File: QiniuService.java    From qiniu with MIT License 6 votes vote down vote up
/**
 * 获取空间的流量统计,使用自定义单位
 */
public XYChart.Series<String, Long> getBucketFlux(String[] domains, String startDate, String endDate, String unit) {
    // 获取流量数据
    CdnResult.FluxResult fluxResult = null;
    try {
        fluxResult = sdkManager.getFluxData(domains, startDate, endDate);
    } catch (QiniuException e) {
        Platform.runLater(() -> DialogUtils.showException(QiniuValueConsts.BUCKET_FLUX_ERROR, e));
    }
    // 设置图表
    XYChart.Series<String, Long> series = new XYChart.Series<>();
    series.setName(QiniuValueConsts.BUCKET_FLUX_COUNT.replaceAll("[A-Z]+", unit));
    // 格式化数据
    if (Checker.isNotNull(fluxResult) && Checker.isNotEmpty(fluxResult.data)) {
        long unitSize = Formatter.sizeToLong("1 " + unit);
        for (Map.Entry<String, CdnResult.FluxData> flux : fluxResult.data.entrySet()) {
            CdnResult.FluxData fluxData = flux.getValue();
            if (Checker.isNotNull(fluxData)) {
                setSeries(fluxResult.time, fluxData.china, fluxData.oversea, series, unitSize);
            }
        }
    }
    return series;
}
 
Example #17
Source File: QiniuOssClient.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * Upload string.
 *
 * @param ossClient   the oss client
 * @param inputStream the input stream
 * @param fileName    the file name
 * @return the string
 */
public String upload(@NotNull UploadManager ossClient, InputStream inputStream, String fileName) {
    try {
        ossClient.put(inputStream, fileName, token, null, null);
        // 拼接 url, 需要正确配置域名 (https://developer.qiniu.com/fusion/kb/1322/how-to-configure-cname-domain-name)
        URL url = new URL(domain);
        log.trace("getUserInfo = {}", url.getUserInfo());
        if (StringUtils.isBlank(url.getPath())) {
            domain = domain + "/";
        } else {
            domain = domain.endsWith("/") ? domain : domain + "/";
        }
        return domain + fileName;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.trace(r.toString());
        try {
            log.trace(r.bodyString());
        } catch (QiniuException ignored) {
        }
    } catch (MalformedURLException e) {
        log.trace("", e);
    }
    return "";
}
 
Example #18
Source File: QiNiuUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 删除图片
 * https://developer.qiniu.com/kodo/sdk/java#rs-batch-delete
 * 每次只能删除小于1000条数据
 *
 * @param list
 */
public void deleteByList(List<String> list) {
    try {
        if (list == null) return;
        log.info("待删除图片大小:{}", list.size());
        String[] keyList = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            keyList[i] = list.get(i).replace(domain, "");
        }
        BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
        batchOperations.addDeleteOp(bucketName, keyList);
        Response response = bucketManager.batch(batchOperations);
        BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
        /*for (int k = 0; k < keyList.length; k++) {
            BatchStatus status = batchStatusList[k];
            if (status.code == 200) {
               // log.info("delete success");
            } else {
                log.error("删除失败", status.toString());
            }
        }*/
    } catch (QiniuException e) {
        log.error("七牛上传 response:" + e.getLocalizedMessage());
    }
}
 
Example #19
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 #20
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 #21
Source File: MdcTopicConsumer.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
 * Handler send sms topic.
 *
 * @param body      the body
 * @param topicName the topic name
 * @param tags      the tags
 * @param keys      the keys
 */
@Transactional(rollbackFor = Exception.class)
public void handlerSendSmsTopic(String body, String topicName, String tags, String keys) throws QiniuException {
	MqMessage.checkMessage(body, keys, topicName);

	if (StringUtils.equals(tags, AliyunMqTopicConstants.MqTagEnum.DELETE_ATTACHMENT.getTag())) {
		List<Long> idList = opcAttachmentService.queryAttachmentByRefNo(body);
		for (final Long id : idList) {
			opcAttachmentService.deleteFile(id);
		}
	} else {
		UpdateAttachmentDto attachmentDto;
		try {
			attachmentDto = JacksonUtil.parseJson(body, UpdateAttachmentDto.class);
		} catch (Exception e) {
			log.error("发送短信MQ出现异常={}", e.getMessage(), e);
			throw new IllegalArgumentException("JSON转换异常", e);
		}
		opcAttachmentService.updateAttachment(attachmentDto);
	}
}
 
Example #22
Source File: QiniuService.java    From qiniu with MIT License 6 votes vote down vote up
/**
 * 日志下载
 */
public void downloadCdnLog(String logDate) {
    if (Checker.isNotEmpty(QiniuApplication.getConfigBean().getBuckets()) && Checker.isDate(logDate)) {
        // 转换域名成数组格式
        String[] domains = new String[QiniuApplication.getConfigBean().getBuckets().size()];
        for (int i = 0; i < QiniuApplication.getConfigBean().getBuckets().size(); i++) {
            domains[i] = QiniuApplication.getConfigBean().getBuckets().get(i).getUrl();
        }
        Map<String, CdnResult.LogData[]> cdnLog = null;
        try {
            cdnLog = sdkManager.listCdnLog(domains, logDate);
        } catch (QiniuException e) {
            DialogUtils.showException(e);
        }
        if (Checker.isNotEmpty(cdnLog)) {
            // 下载日志
            for (Map.Entry<String, CdnResult.LogData[]> logs : cdnLog.entrySet()) {
                for (CdnResult.LogData log : logs.getValue()) {
                    QiniuUtils.download(log.url);
                }
            }
        }
    }
}
 
Example #23
Source File: FileService.java    From ml-blog with MIT License 6 votes vote down vote up
/**
 * 文件删除
 * @param key
 * @return
 */
public Response delete(String key) throws GlobalException{

    // 有配置数据,但上传凭证为空
    if (!commonMap.containsKey("upToken")) {
        // 创建七牛云组件
        createQiniuComponent();
    }

    try {
        BucketManager bucketManager = (BucketManager) commonMap.get("bucketManager");
        String bucket = commonMap.get("qn_bucket").toString();
        Response response = bucketManager.delete(bucket, key);
        int retry = 0;
        while(response.needRetry() && retry < 3) {
            response = bucketManager.delete(bucket, key);
            retry++;
        }
        return response;
    } catch (QiniuException ex) {
        log.error("文件删除异常:",ex.toString());
        throw new GlobalException(500, ex.toString());
    }
}
 
Example #24
Source File: QiniuDemo.java    From zheng with MIT License 6 votes vote down vote up
public void upload() throws IOException {
	try {
		//调用put方法上传
		Response res = uploadManager.put(filePath, key, getUpToken());
		//打印返回的信息
		System.out.println(res.bodyString());
	} catch (QiniuException e) {
		Response r = e.response;
		// 请求失败时打印的异常的信息
		System.out.println(r.toString());
		try {
			//响应的文本信息
			System.out.println(r.bodyString());
		} catch (QiniuException e1) {
			//ignore
		}
	}
}
 
Example #25
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 #26
Source File: UploadConfiguration.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
static String uploadFile(File file, String folder) {
    UploadManager uploadManager = UploadConfiguration.getUploadManager();

    if (!file.exists()) {
        throw new RuntimeException("上传的文件不存在");
    }
    StringBuilder builder = new StringBuilder();
    if (!StringUtils.isNullOrEmpty(folder)) {
        builder.append(folder);
    }
    builder.append(file.getName());

    try {
        Response response = uploadManager.put(file, builder.toString(), UploadConfiguration.getToken());
        if (response.isOK()) {
            return JSON.parseObject(response.bodyString(), DefaultPutRet.class).key;
        }

    } catch (QiniuException e) {
        throw new RuntimeException("上传文件失败");
    }
    return null;
}
 
Example #27
Source File: FileService.java    From ml-blog with MIT License 5 votes vote down vote up
/**
 * 文件上传
 * @param inputStream
 * @param filename
 * @return
 */
public Response upload(InputStream inputStream, String filename) throws GlobalException{

    // 有配置数据,但上传凭证为空
    if (!commonMap.containsKey("upToken")) {
        // 创建七牛云组件
        createQiniuComponent();
    }

    try {

        String upToken = (String) commonMap.get("upToken");
        UploadManager uploadManager = (UploadManager) commonMap.get("uploadManager");
        // 上传
        Response response = uploadManager.put(inputStream,filename,upToken,null, null);
        int retry = 0;
        while(response.needRetry() && retry < 3) {
            response = uploadManager.put(inputStream,filename,upToken,null, null);
            retry++;
        }

        return response;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.error("文件上传异常:",r.toString());
        throw new GlobalException(500, ex.toString());
    }
}
 
Example #28
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 #29
Source File: QiniuServiceImpl.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Override
public String uploadToByte(byte[] data, String fileName) {
    try {
        Response response = uploadManager.put(data, fileName, this.getToken());
        if (response.isOK()) {
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        }
    } catch (QiniuException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #30
Source File: QiniuService.java    From qiniu with MIT License 5 votes vote down vote up
/**
 * 批量删除文件,单次批量请求的文件数量不得超过1000
 */
public void deleteFile(ObservableList<FileBean> fileBeans, String bucket) {
    if (Checker.isNotEmpty(fileBeans) && QiniuUtils.checkNet()) {
        // 生成待删除的文件列表
        String[] files = new String[fileBeans.size()];
        ArrayList<FileBean> selectedFiles = new ArrayList<>();
        int i = 0;
        for (FileBean fileBean : fileBeans) {
            files[i++] = fileBean.getName();
            selectedFiles.add(fileBean);
        }
        try {
            BatchStatus[] batchStatusList = sdkManager.batchDelete(bucket, files);
            MainController main = MainController.getInstance();
            // 文件列表是否为搜索后结果
            boolean isInSearch = Checker.isNotEmpty(main.searchTF.getText());
            ObservableList<FileBean> currentRes = main.resTV.getItems();
            // 更新界面数据
            for (i = 0; i < files.length; i++) {
                BatchStatus status = batchStatusList[i];
                String file = files[i];
                if (status.code == 200) {
                    main.getResData().remove(selectedFiles.get(i));
                    main.setDataLength(main.getDataLength() - 1);
                    main.setDataSize(main.getDataSize() - Formatter.sizeToLong(selectedFiles.get(i).getSize()));
                    if (isInSearch) {
                        currentRes.remove(selectedFiles.get(i));
                    }
                } else {
                    LOGGER.error("delete " + file + " failed, message -> " + status.data.error);
                    DialogUtils.showError("删除文件:" + file + " 失败");
                }
            }
        } catch (QiniuException e) {
            DialogUtils.showException(QiniuValueConsts.DELETE_ERROR, e);
        }
        MainController.getInstance().countBucket();
    }
}