com.qiniu.http.Response Java Examples

The following examples show how to use com.qiniu.http.Response. 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: UploadConfiguration.java    From spring-cloud-shop with MIT License 7 votes vote down vote up
static String uploadStream(InputStream is, String fileName) {
    UploadManager uploadManager = UploadConfiguration.getUploadManager();
    try {

        String key = SysConfigMap.get(SysConfigKeys.QINIU_BUCKET) + '/' + DateUtils.format(LocalDateTime.now(), DateUtils.NORM_DATE_PATTERN) + "/" + fileName;
        Response response = uploadManager.put(is, key, UploadConfiguration.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: 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 #3
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 #4
Source File: QiNiuCloudTemplate.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SneakyThrows
private OssFile upload(String bucketName, String fileName, InputStream stream, boolean cover) {
	// 创建存储桶
	createBucket(bucketName);
	// 获取 oss 存储文件名
	String key = getFileName(fileName);

	// 是否覆盖上传
	if (cover) {
		uploadManager.put(stream, key, getUploadToken(bucketName, key), null, null);
	} else {
		Response response = uploadManager.put(stream, key, getUploadToken(bucketName), null, null);
		int retry = 0;
		int retryCount = 5;
		while (response.needRetry() && retry < retryCount) {
			response = uploadManager.put(stream, key, getUploadToken(bucketName), null, null);
			retry++;
		}
	}

	OssFile ossFile = new OssFile();
	ossFile.setName(key);
	ossFile.setOriginalName(fileName);
	ossFile.setLink(getFileLink(bucketName, key));
	return ossFile;
}
 
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: 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 #7
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 #8
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 #9
Source File: QiNiuCloudUtil.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
/**
 *  base64方式上传
 * @param base64 :图片编码
 * @param fileName:图片名称
 * @return
 * @throws Exception
 */
public static String uploadPicByBase64(byte[] base64, String fileName) throws Exception{
    String file64 = Base64.encodeToString(base64, 0);
    Integer length = base64.length;
    String dateStr = LocalDate.now().toString();
    // 将当前日期拼接在文件名称中
    fileName = dateStr + "/" + fileName;
    String url = "http://upload.qiniu.com/putb64/" + length + "/key/"+ UrlSafeBase64.encodeToString(fileName);
    //非华东空间需要根据注意事项 : 修改上传域名
    RequestBody requestBody = RequestBody.create(null, file64);
    Request request = new Request.Builder()
            .url(url)
            .addHeader("Content-Type", "application/octet-stream")
            .addHeader("Authorization", "UpToken " + getUpToken())
            .post(requestBody).build();
    OkHttpClient client = new OkHttpClient();
    okhttp3.Response response = client.newCall(request).execute();
    // 上传成功返回图片地址
    return response.isSuccessful()?("http://" + bucketNameUrl + "/" + fileName):"Up Img Failed";
}
 
Example #10
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 #11
Source File: QiNiuUtils.java    From ClipIt with MIT License 6 votes vote down vote up
private static String parserQiniuResponseResult(Response response) throws QiniuException {
    //解析上传成功的结果
    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    String prefix = properties.getProperty("markdown.prefix");
    String suffix = properties.getProperty("markdown.suffix");
    String result;
    String key = putRet.key;
    String fileName = key.substring(key.indexOf("_", key.indexOf("_") + 1) + 1);
    if (!fileName.startsWith("clipboard")) {
        prefix = prefix.replace("image", fileName);
    }
    try {
        result = String.format("%s%s%s", prefix, bucketDomain + "/" + URLEncoder.encode(key, "utf-8").replace("+", "%20"), suffix);

    } catch (UnsupportedEncodingException e) {
        // e.printStackTrace();
        result = String.format("%s%s%s", prefix, bucketDomain + "/" + key, suffix);
    }
    // System.out.println(result);
    return result;
}
 
Example #12
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 #13
Source File: QiniuService.java    From expper with GNU General Public License v3.0 6 votes vote down vote up
public QiniuResult uploadPicture(String login, MultipartFile picture) throws IOException {
    User user = userRepository.findByLogin(login);
    String key = pictureKey(user.getId());
    String token = authToken(key);

    File file = convert(picture);
    Response res = uploadManager.put(file, key, token, null, null, true);
    QiniuResult result = res.jsonToObject(QiniuResult.class);

    file.delete();

    user.setPicture(key);
    userRepository.save(user);

    return result;
}
 
Example #14
Source File: OptQiniuOssServiceImpl.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> batchDeleteFile(String[] fileNameList, String bucketName) throws QiniuException {
	log.info("batchDeleteFile - 删除OSS文件. fileNameList={}, bucketName={}", fileNameList, bucketName);
	BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
	batchOperations.addDeleteOp(bucketName, fileNameList);

	Response response = bucketManager.batch(batchOperations);
	BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);

	Set<String> failSet = Sets.newHashSet();
	for (int i = 0; i < fileNameList.length; i++) {
		BatchStatus status = batchStatusList[i];
		String fileName = fileNameList[i];
		if (status.code != 200) {
			failSet.add(fileName);
			log.error("batchDeleteFile - 删除OSS文件. [FAIL] fileName={}, error={}", fileName, status.data.error);
		} else {
			log.info("batchDeleteFile - 删除OSS文件. [OK] fileName={}, bucketName={}", fileName, bucketName);
		}
	}
	return failSet;
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: QiniuApiClient.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 删除七牛空间图片方法
 *
 * @param key 七牛空间中文件名称
 */
@Override
public boolean removeFile(String key) {
    this.check();

    if (StringUtils.isNullOrEmpty(key)) {
        throw new QiniuApiException("[" + this.storageType + "]删除文件失败:文件key为空");
    }
    Auth auth = Auth.create(this.accessKey, this.secretKey);
    Configuration config = new Configuration(Region.autoRegion());
    BucketManager bucketManager = new BucketManager(auth, config);
    try {
        Response re = bucketManager.delete(this.bucket, key);
        return re.isOK();
    } catch (QiniuException e) {
        Response r = e.response;
        throw new QiniuApiException("[" + this.storageType + "]删除文件发生异常:" + r.toString());
    }
}
 
Example #22
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 #23
Source File: QiniuTemplate.java    From blade-tool with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SneakyThrows
public BladeFile put(String bucketName, InputStream stream, String key, boolean cover) {
	makeBucket(bucketName);
	key = getFileName(key);
	// 覆盖上传
	if (cover) {
		uploadManager.put(stream, key, getUploadToken(bucketName, key), null, null);
	} else {
		Response response = uploadManager.put(stream, key, getUploadToken(bucketName), null, null);
		int retry = 0;
		int retryCount = 5;
		while (response.needRetry() && retry < retryCount) {
			response = uploadManager.put(stream, key, getUploadToken(bucketName), null, null);
			retry++;
		}
	}
	BladeFile file = new BladeFile();
	file.setName(key);
	file.setLink(fileLink(bucketName, key));
	return file;
}
 
Example #24
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 #25
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 #26
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
/***
 * 上传本地图片
 * @param src
 * @return
 */
public static String uploadLocalImg(String src) throws IOException, NoSuchAlgorithmException{
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	UploadManager uploadManager = new UploadManager(config);
	Auth auth = Auth.create(qiniuAccess, qiniuKey);
	String token = auth.uploadToken(bucketName);
	File file = new File(src);
	if(!file.exists()){
		throw new MyException("本地文件不存在");
	}
	QETag tag = new QETag();
	String hash = tag.calcETag(file);
	Rescource rescource = new Rescource();
	EntityWrapper<RestResponse> wrapper = new EntityWrapper<>();
	wrapper.eq("hash",hash);
	rescource = rescource.selectOne(wrapper);
	if( rescource!= null){
		return rescource.getWebUrl();
	}
	String filePath="",
			extName = "",
	name = UUID.randomUUID().toString();
	extName = file.getName().substring(
			file.getName().lastIndexOf("."));
	Response response = uploadManager.put(file,name,token);
	if(response.isOK()){
		filePath = path + name;
		rescource = new Rescource();
		rescource.setFileName(name);
		rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.length()/1024)+"kb");
		rescource.setHash(hash);
		rescource.setFileType(StringUtils.isBlank(extName)?"unknown":extName);
		rescource.setWebUrl(filePath);
		rescource.setSource("qiniu");
		rescource.insert();
	}
	return filePath;
}
 
Example #27
Source File: QiniuCloudStorageService.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@Override
public String upload(byte[] data, String path) {
    try {
        Response res = uploadManager.put(data, path, token);
        if (!res.isOK()) {
            throw new RuntimeException("上传七牛出错:" + res.toString());
        }
    } catch (Exception e) {
        throw new RRException("上传文件失败,请核对七牛配置信息", e);
    }

    return config.getQiniuDomain() + "/" + path;
}
 
Example #28
Source File: OptQiniuOssServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
@Retryable(value = Exception.class, backoff = @Backoff(delay = 5000, multiplier = 2))
public void deleteFile(String fileName, String bucketName) throws QiniuException {
	log.info("deleteFile - 删除OSS文件. fileName={}, bucketName={}", fileName, bucketName);

	Preconditions.checkArgument(StringUtils.isNotEmpty(fileName), ErrorCodeEnum.OPC10040010.msg());
	Preconditions.checkArgument(StringUtils.isNotEmpty(bucketName), "存储空间不能为空");


	Response response = bucketManager.delete(bucketName, fileName);
	log.info("deleteFile - 删除OSS文件. [OK] response={}", response);
}
 
Example #29
Source File: QiniuProvider.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 处理上传结果,返回文件url
 * 
 * @return
 * @throws QiniuException
 */
private String processUploadResponse(Response res) throws QiniuException {
	if (res.isOK()) {
		UploadResult ret = res.jsonToObject(UploadResult.class);
		return getFullPath(ret.key);
	}
	throw new FSOperErrorException(name(), res.toString());
}
 
Example #30
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;
}