Java Code Examples for com.qiniu.http.Response

The following examples show how to use com.qiniu.http.Response. These examples are extracted from open source projects. 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 Project: javabase   Author: ggj2010   File: QiNiuUtil.java    License: 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 #2
Source Project: uexam   Author: alvis-u   File: FileUploadImpl.java    License: 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 Project: BigDataPlatform   Author: KangU4   File: QiniuUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String qiniuBase64Upload(String data64){

        String key = renamePic(".png");
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        //服务端http://up-z2.qiniup.com
        String url = "http://up-z2.qiniup.com/putb64/-1/key/"+ UrlSafeBase64.encodeToString(key);
        RequestBody rb = RequestBody.create(null, data64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return origin+key;
    }
 
Example #4
Source Project: uexam-mysql   Author: alvis-u   File: FileUploadImpl.java    License: 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 #5
Source Project: magic-starter   Author: xkcoding   File: QiNiuCloudTemplate.java    License: 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 #6
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClient.java    License: 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 #7
Source Project: markdown-image-kit   Author: dong4j   File: QiniuOssClientTest.java    License: 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 #8
Source Project: SpringBoot-Home   Author: vanDusty   File: QiNiuCloudUtil.java    License: 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 #9
Source Project: spring-cloud-shop   Author: SiGuiyang   File: UploadConfiguration.java    License: MIT License 6 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 #10
Source Project: spring-cloud-shop   Author: SiGuiyang   File: UploadConfiguration.java    License: 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 Project: ClipIt   Author: scruel   File: QiNiuUtils.java    License: 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 Project: spring-cloud-shop   Author: SiGuiyang   File: QiniuServiceImpl.java    License: 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 Project: expper   Author: Raysmond   File: QiniuService.java    License: 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 Project: ml-blog   Author: moonlightL   File: FileService.java    License: 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 #15
Source Project: paascloud-master   Author: paascloud   File: OptQiniuOssServiceImpl.java    License: 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 #16
Source Project: rebuild   Author: getrebuild   File: QiniuCloud.java    License: 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 #17
Source Project: blade-tool   Author: chillzhuang   File: QiniuTemplate.java    License: 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 #18
Source Project: mysiteforme   Author: wangl1989   File: QiniuUploadServiceImpl.java    License: 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 #19
Source Project: OneBlog   Author: zhangyd-c   File: QiniuApiClient.java    License: 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 #20
Source Project: zheng   Author: shuzheng   File: QiniuDemo.java    License: 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 Project: jeesuite-libs   Author: vakinge   File: QiniuProvider.java    License: 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 #22
Source Project: newblog   Author: Zephery   File: QiniuUtil.java    License: 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 #23
Source Project: newblog   Author: Zephery   File: QiniuUtil.java    License: 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 #24
Source Project: mblog   Author: langhsu   File: QiniuStorageImpl.java    License: 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 #25
Source Project: sanshanblog   Author: SanShanYouJiu   File: QiniuStorageManager.java    License: 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 #26
Source Project: sk-admin   Author: DengSinkiang   File: QiNiuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
    FileUtils.checkSize(maxSize, file.getSize());
    if (qiniuConfig.getId() == null) {
        throw new SkException("请先添加相应配置,再操作");
    }
    // 构造一个带指定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 (qiniuContentDao.findByKey(key) != null) {
            key = QiNiuUtil.getKey(key);
        }
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        //解析上传成功的结果

        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        //存入数据库
        QiniuContent qiniuContent = new QiniuContent();
        qiniuContent.setSuffix(FileUtils.getExtensionName(putRet.key));
        qiniuContent.setBucket(qiniuConfig.getBucket());
        qiniuContent.setType(qiniuConfig.getType());
        qiniuContent.setKey(FileUtils.getFileNameNoEx(putRet.key));
        qiniuContent.setUrl(qiniuConfig.getHost() + "/" + putRet.key);
        qiniuContent.setSize(FileUtils.getSize(Integer.parseInt(file.getSize() + "")));
        return qiniuContentDao.save(qiniuContent);
    } catch (Exception e) {
        throw new SkException(e.getMessage());
    }
}
 
Example #27
Source Project: WePush   Author: rememberber   File: QiNiuYunMsgSender.java    License: MIT License 5 votes vote down vote up
@Override
    public SendResult send(String[] msgData) {
        SendResult sendResult = new SendResult();
        try {
            String templateId = QiNiuYunMsgMaker.templateId;
            Map<String, String> params = qiNiuYunMsgMaker.makeMsg(msgData);
            String telNum = msgData[0];

            if (PushControl.dryRun) {
                sendResult.setSuccess(true);
                return sendResult;
            } else {
                Response resp = smsManager.sendMessage(templateId, new String[]{telNum}, params);

//                if (resp.statusCode == 200) {
                sendResult.setSuccess(true);
//                } else {
//                    sendResult.setSuccess(false);
//                    sendResult.setInfo(resp.error);
//                }
            }
        } catch (Exception e) {
            sendResult.setSuccess(false);
            sendResult.setInfo(e.getMessage());
            log.error(ExceptionUtils.getStackTrace(e));
        }

        return sendResult;
    }
 
Example #28
Source Project: microservice-recruit   Author: stalary   File: QiNiuService.java    License: 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 #29
Source Project: smart-admin   Author: 1024-lab   File: FileServiceQiNiuYun.java    License: 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);
}
 
Example #30
Source Project: smart-admin   Author: 1024-lab   File: FileServiceQiNiuYun.java    License: MIT License 5 votes vote down vote up
/**
 * 获取文件
 */
public File getFile(String key, String fileName) {
    String finalUrl = getDownloadUrl(key);
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(finalUrl).build();
    okhttp3.Response resp = null;
    File file = new File(fileName);
    try {
        resp = client.newCall(req).execute();
        if (resp.isSuccessful()) {
            ResponseBody body = resp.body();
            InputStream objectContent = body.byteStream();
            // 输入流转换为字节流
            byte[] buffer = FileCopyUtils.copyToByteArray(objectContent);
            // 字节流写入文件
            FileCopyUtils.copy(buffer, file);
            // 关闭输入流
            objectContent.close();
        }

    } catch (IOException e) {
        log.error("文件获取失败:" + e);
        return null;
    } finally {
    }
    return file;
}