Java Code Examples for com.qiniu.http.Response#isOK()

The following examples show how to use com.qiniu.http.Response#isOK() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: QiniuStorageImpl.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
    String accessKey = options.getValue(oss_key);
    String secretKey = options.getValue(oss_secret);
    String domain = options.getValue(oss_domain);
    String bucket = options.getValue(oss_bucket);
    String src = options.getValue(oss_src);

    if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
        throw new MtonsException("请先在后台设置阿里云配置信息");
    }

    if (StringUtils.isNotBlank(src)) {
        if (src.startsWith("/")) {
            src = src.substring(1);
        }

        if (!src.endsWith("/")) {
            src = src + "/";
        }
    } else {
        src = "";
    }

    String key = UpYunUtils.md5(bytes);
    String path = src + key + FileKit.getSuffix(pathAndFileName);

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket, path);

    UploadManager uploadManager = new UploadManager(configuration);
    Response response = uploadManager.put(bytes, path, upToken);

    if (!response.isOK()) {
        throw new MtonsException(response.bodyString());
    }
    return domain.trim() + "/" + path;
}
 
Example 11
Source File: QiniuProvider.java    From azeroth 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 12
Source File: QiniuCloud.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 文件上传
 * 
 * @param file
 * @return
 * @throws IOException
 */
public String upload(File file) throws IOException {
	Assert.notNull(auth, "云存储账户未配置");
	String key = formatFileKey(file.getName()); 
	Response resp = UPLOAD_MANAGER.put(file, key, auth.uploadToken(bucketName));
	if (resp.isOK()) {
		return key;
	} else {
		LOG.error("文件上传失败 : " + resp);
		return null;
	}
}
 
Example 13
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 14
Source File: QiNiuService.java    From microservice-recruit with Apache License 2.0 5 votes vote down vote up
public String uploadPicture(MultipartFile picture, String name) {
    try {
        Response response = uploadManager.put(picture.getBytes(), name, getUpToken());
        if (response.isOK() && response.isJson()) {
            return QINIU_IMAGE_DOMAIN + name;
        }
    } catch (Exception e) {
        log.warn("upload picture error", e);
        throw new MyException(ResultEnum.QINIU_ERROR);
    }
    return QINIU_IMAGE_DOMAIN + name;
}
 
Example 15
Source File: QiniuCloudStorageService.java    From renren-fast with GNU General Public License v3.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 16
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 17
Source File: UploadConfiguration.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
/**
 * 字节数组上传
 *
 * @param data     字节数组
 * @param fileName 文件名
 */
static String uploadToByte(byte[] data, String fileName) {
    UploadManager uploadManager = UploadConfiguration.getUploadManager();
    try {
        Response response = uploadManager.put(data, fileName, UploadConfiguration.getToken());
        if (response.isOK()) {
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        }
    } catch (QiniuException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 18
Source File: UploadController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example 19
Source File: UploadController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example 20
Source File: FileServiceQiNiuYun.java    From smart-admin with MIT License 5 votes vote down vote up
@Override
public ResponseDTO<UploadVO> fileUpload(MultipartFile multipartFile, String path) {
    OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
    try {
        InputStream inputStream = new ByteArrayInputStream(multipartFile.getBytes());
        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 uuid = UUID.randomUUID().toString().replace("-", "");
        String ossPath = path + "/" + uuid;
        String fileName = multipartFile.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
        String mime = this.getContentType(fileExt);
        Response res = ossClient.put(inputStream, ossPath, token, null, mime);
        if (! res.isOK()) {
            log.error("QINIU fileUpload ERROR : {}", res.toString());
            return ResponseDTO.wrap(FileResponseCodeConst.UPLOAD_ERROR);
        }
        UploadVO localUploadVO = new UploadVO();
        localUploadVO.setUrl(this.getFileUrl(ossPath).getData());
        localUploadVO.setFileName(fileName);
        localUploadVO.setFilePath(ossPath);
        localUploadVO.setFileSize(multipartFile.getSize());
        return ResponseDTO.succData(localUploadVO);
    } catch (Exception e) {
        log.error("QINIU fileUpload ERROR : {}", e);
    }
    return ResponseDTO.wrap(FileResponseCodeConst.UPLOAD_ERROR);
}