com.qiniu.storage.model.DefaultPutRet Java Examples

The following examples show how to use com.qiniu.storage.model.DefaultPutRet. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: QiniuServiceImpl.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
@Override
public String uploadFile(File file, String folder) {

    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(), this.getToken());
        if (response.isOK()) {
            return JSON.parseObject(response.bodyString(), DefaultPutRet.class).key;
        }

    } catch (QiniuException e) {
        throw new RuntimeException("上传文件失败");
    }
    return null;
}
 
Example #11
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 #12
Source File: QiNiuServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
    FileUtil.checkSize(maxSize, file.getSize());
    if(qiniuConfig.getId() == null){
        throw new BadRequestException("请先添加相应配置,再操作");
    }
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
    String upToken = auth.uploadToken(qiniuConfig.getBucket());
    try {
        String key = file.getOriginalFilename();
        if(qiniuContentRepository.findByKey(key) != null) {
            key = QiNiuUtil.getKey(key);
        }
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        //解析上传成功的结果

        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        QiniuContent content = qiniuContentRepository.findByKey(FileUtil.getFileNameNoEx(putRet.key));
        if(content == null){
            //存入数据库
            QiniuContent qiniuContent = new QiniuContent();
            qiniuContent.setSuffix(FileUtil.getExtensionName(putRet.key));
            qiniuContent.setBucket(qiniuConfig.getBucket());
            qiniuContent.setType(qiniuConfig.getType());
            qiniuContent.setKey(FileUtil.getFileNameNoEx(putRet.key));
            qiniuContent.setUrl(qiniuConfig.getHost()+"/"+putRet.key);
            qiniuContent.setSize(FileUtil.getSize(Integer.parseInt(file.getSize()+"")));
            return qiniuContentRepository.save(qiniuContent);
        }
        return content;
    } catch (Exception e) {
       throw new BadRequestException(e.getMessage());
    }
}
 
Example #13
Source File: QiniuUtils.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 上传二进制数据,返回 文件的 UIR
 *
 * @param data
 * @param fileKey
 * @return String
 * @throws IOException
 */
public String upload(byte[] data, String fileKey) throws IOException {
    Response res;
    try {
        res = getUploadManager().put(data, fileKey, getUpToken(fileKey));
        DefaultPutRet putRet = JsonUtils.jsonToPojo(res.body(), DefaultPutRet.class);
        return fileDomain + "/" + putRet.key;
    } catch (QiniuException e) {
        res = e.response;
        e.printStackTrace();
        return "上传失败";
    }
}
 
Example #14
Source File: QiNiuServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public QiNiuContent upload(MultipartFile file) {
    //获取七牛云信息
    QiNiuConfig qiNiuConfig = getQiNiuConfig();
    if (!qiNiuConfig.check()) {
        throw new CustomException("七牛云配置信息不完整,请先填写七牛云配置信息");
    }
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(QiNiuUtils.getRegion(qiNiuConfig.getZone()));
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
    //生成上传文件Token
    String upToken = auth.uploadToken(qiNiuConfig.getBucket());
    QiNiuContent qiNiuContent = new QiNiuContent();
    try {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = FileUtils.getFileNameNoExtension(file.getOriginalFilename()) + df.format(new Date()) + "." + FileUtils.getExtensionName(file.getOriginalFilename());
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        //解析
        DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        //将结果存入数据库
        qiNiuContent.setSuffix(FileUtils.getExtensionName(defaultPutRet.key));
        qiNiuContent.setBucket(qiNiuConfig.getBucket());
        qiNiuContent.setType(qiNiuConfig.getType());
        qiNiuContent.setName(FileUtils.getFileNameNoExtension(defaultPutRet.key));
        qiNiuContent.setUrl("http://" + qiNiuConfig.getHost() + "/" + defaultPutRet.key);
        qiNiuContent.setSize(FileUtils.getSizeString(Integer.parseInt(file.getSize() + "")));
        qiNiuContentMapper.insertContent(qiNiuContent);
    } catch (Exception e) {
        throw new CustomException(e.getMessage());
    }
    return qiNiuContent;
}
 
Example #15
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 #16
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 #17
Source File: UploadController.java    From ml-blog with MIT License 5 votes vote down vote up
/**
 * markdown 编辑器专用文件上传
 * @param request
 * @param response
 * @param attach
 * @return
 */
@SysLog("mdUploadfile 文件上传")
@PostMapping("/mdUploadfile")
@ResponseBody
public FileResult mdUploadfile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "editormd-image-file", required = false) MultipartFile attach) throws GlobalException{
    try {

        if (!ParamUtil.checkParameter(ParamConstant.QINIU)) {
            throw new GlobalException(500,"未配置七牛云参数");
        }

        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/json");

        Response resp = this.fileService.upload(attach.getInputStream(), attach.getOriginalFilename());
        if (!resp.isOK()) {
            log.error("文件上传失败 -> url:{},Response:{}","/mdUploadfile",resp);
            throw new GlobalException(500,"文件上传失败");
        }
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(resp.bodyString(), DefaultPutRet.class);

        String resultKey = putRet.key == null ? putRet.hash : putRet.key;

        //下面response返回的json格式是editor.md所限制的,规范输出就OK
        return FileResult.success(commonMap.get("qn_domain").toString() + "/" + resultKey);

    } catch (Exception e) {
        throw new GlobalException(500,e.getMessage());
    }
}
 
Example #18
Source File: OptQiniuOssServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public OptUploadFileRespDto uploadFile(byte[] uploadBytes, String fileName, String filePath, String bucketName) throws IOException {
	log.info("uploadFile - 上传文件. fileName={}, bucketName={}", fileName, bucketName);

	Preconditions.checkArgument(uploadBytes != null, "读取文件失败");
	Preconditions.checkArgument(StringUtils.isNotEmpty(fileName), ErrorCodeEnum.OPC10040010.msg());
	Preconditions.checkArgument(StringUtils.isNotEmpty(filePath), "文件路径不能为空");
	Preconditions.checkArgument(StringUtils.isNotEmpty(bucketName), "存储节点不能为空");

	InputStream is = new ByteArrayInputStream(uploadBytes);
	String inputStreamFileType = FileTypeUtil.getType(is);
	String newFileName = UniqueIdGenerator.generateId() + "." + inputStreamFileType;

	// 检查数据大小
	this.checkFileSize(uploadBytes);

	Response response = uploadManager.put(uploadBytes, filePath + newFileName, getUpToken(bucketName));
	DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
	log.info("uploadFile - 上传文件. [OK] putRet={}", putRet);
	if (PublicUtil.isEmpty(putRet) || StringUtils.isEmpty(putRet.key)) {
		throw new OpcBizException(ErrorCodeEnum.OPC10040009);
	}
	String fileUrl;
	// 获取图片路径
	if (StringUtils.equals(OPEN_IMG_BUCKET, bucketName)) {
		fileUrl = paascloudProperties.getQiniu().getOss().getPublicHost() + "/" + filePath + newFileName;
	} else {
		String domainUrl = paascloudProperties.getQiniu().getOss().getPrivateHost();
		fileUrl = this.getFileUrl(domainUrl, fileName);
	}
	OptUploadFileRespDto result = new OptUploadFileRespDto();
	result.setAttachmentUrl(fileUrl);
	result.setAttachmentName(newFileName);
	result.setAttachmentPath(filePath);
	return result;
}
 
Example #19
Source File: QiniuOssUtil.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
public static String upload(FileInputStream file, String fileName) {
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    // 其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    try {
        Auth auth = Auth.create(properies.getOss().getQiniu().getAccessKey(), properies.getOss().getQiniu().getSecretKey());
        String upToken = auth.uploadToken(properies.getOss().getQiniu().getBucket());
        try {
            Response response = uploadManager.put(file, fileName, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            return properies.getOss().getQiniu().getPath() + "/" + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.error(r.toString());
            try {
                logger.error(r.bodyString());
            } catch (QiniuException ignore) {

            }
        }
    } catch (Exception e) {
        logger.error("error", e);
    }
    return null;
}
 
Example #20
Source File: QiniuApiClient.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 上传图片
 *
 * @param is       图片流
 * @param imageUrl 图片路径
 * @return 上传后的路径
 */
@Override
public VirtualFile uploadImg(InputStream is, String imageUrl) {
    this.check();

    String key = FileUtil.generateTempFileName(imageUrl);
    this.createNewFileName(key, this.pathPrefix);
    Date startTime = new Date();
    //Zone.zone0:华东
    //Zone.zone1:华北
    //Zone.zone2:华南
    //Zone.zoneNa0:北美
    Configuration cfg = new Configuration(Region.autoRegion());
    UploadManager uploadManager = new UploadManager(cfg);
    try {
        Auth auth = Auth.create(this.accessKey, this.secretKey);
        String upToken = auth.uploadToken(this.bucket);
        Response response = uploadManager.put(is, this.newFileName, upToken, null, null);

        //解析上传成功的结果
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

        return new VirtualFile()
                .setOriginalFileName(key)
                .setSuffix(this.suffix)
                .setUploadStartTime(startTime)
                .setUploadEndTime(new Date())
                .setFilePath(putRet.key)
                .setFileHash(putRet.hash)
                .setFullFilePath(this.path + putRet.key);
    } catch (QiniuException ex) {
        throw new QiniuApiException("[" + this.storageType + "]文件上传失败:" + ex.error());
    }
}
 
Example #21
Source File: QiniuCloudService.java    From my-site with Apache License 2.0 5 votes vote down vote up
public String upload(MultipartFile file, String fileName) {

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response response = null;

            response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example #22
Source File: QiniuUtils.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 上传输入流,返回 文件的 UIR
 *
 * @param inputStream
 * @param fileKey
 * @return String
 * @throws IOException
 */
public String upload(InputStream inputStream, String fileKey) throws IOException {
    Response res;
    try {
        res = getUploadManager().put(inputStream, fileKey, getUpToken(fileKey), null, null);
        DefaultPutRet putRet = JsonUtils.jsonToPojo(res.body(), DefaultPutRet.class);
        return fileDomain + "/" + putRet.key;
    } catch (QiniuException e) {
        res = e.response;
        e.printStackTrace();
        return "上传失败";
    }
}
 
Example #23
Source File: QiNiuServiceImpl.java    From sk-admin with 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 #24
Source File: QiniuUtils.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 将本地文件上传
 *
 * @param filePath 本地文件路径
 * @param fileKey  上传到七牛后保存的文件路径名称
 * @return String
 * @throws IOException
 */
public String upload(String filePath, String fileKey) throws IOException {
    Response res;
    try {
        res = getUploadManager().put(filePath, fileKey, getUpToken(fileKey));
        DefaultPutRet putRet = JsonUtils.jsonToPojo(res.body(), DefaultPutRet.class);
        return fileDomain + "/" + putRet.key;
    } catch (QiniuException e) {
        res = e.response;
        log.error(e.getMessage());
        return "上传失败";
    }
}
 
Example #25
Source File: QiNiuUploadFileTemplateServiceImpl.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public String doSaveFileStore(final MultipartFile file) {
    final Configuration cfg = new Configuration(Zone.autoZone());
    final UploadManager uploadManager = new UploadManager(cfg);
    final Auth auth = Auth.create(ConfigCache.getConfig(Constants.QINIU_ACCESS_KEY), ConfigCache.getConfig(Constants.QINIU_SECRET_KEY));
    final String upToken = auth.uploadToken(ConfigCache.getConfig(Constants.QINIU_BUCKET));
    try {
        final Response response = uploadManager.put(file.getInputStream(), FileUtil.createSingleFileName(file.getOriginalFilename()), upToken, null, null);
        final DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return ConfigCache.getConfig(Constants.QINIU_IMAGE_DOMAIN) + putRet.key;
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #26
Source File: KODOImageupload.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 客户端接口
 * */
public Map<ReturnImage, Integer> clientuploadKODO(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
    File file = null;
    Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
    for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
        java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
        String times = format1.format(new Date());
        file = SetFiles.changeFile(entry.getValue());
        System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
        try {
            ReturnImage returnImage = new ReturnImage();
            if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
                Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                returnImage.setImgname(entry.getValue().getOriginalFilename());
                returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
                ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
            }else{
                returnImage.setImgname(entry.getValue().getOriginalFilename());
                returnImage.setImgurl("文件超出系统设定大小,不得超过");
                ImgUrl.put(returnImage, -1);
            }
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
            }
        }
    }
    return ImgUrl;
}
 
Example #27
Source File: QiniuOssClientTest.java    From markdown-image-kit with MIT License 5 votes vote down vote up
public static String upload(File file, String bucket, String accessKey, String secretKey, String endpoint) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释

    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = "test.png";

    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    BucketManager bucketManager = new BucketManager(auth, cfg);

    try {
        Response response = uploadManager.put(file, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info(putRet.key);
        log.info(putRet.hash);

        FileInfo fileInfo = bucketManager.stat(bucket, key);
        System.out.println(fileInfo.hash);
        System.out.println(fileInfo.fsize);
        System.out.println(fileInfo.mimeType);
        System.out.println(fileInfo.putTime);
        return endpoint + key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.info(r.toString());
        try {
            log.info(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
    return "";
}
 
Example #28
Source File: QiniuOssClientTest.java    From markdown-image-kit with MIT License 5 votes vote down vote up
public static String upload(InputStream inputStream, String bucket, String preFix, String accessKey, String secretKey) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释

    UploadManager uploadManager = new UploadManager(cfg);

    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = null;

    byte[] uploadBytes = "hello qiniu cloud".getBytes(StandardCharsets.UTF_8);
    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);

    try {
        Response response = uploadManager.put(byteInputStream, 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.info(r.toString());
        try {
            log.info(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }

    return "";
}
 
Example #29
Source File: QiNiuUtil.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 上传七牛云
 *
 * @param uploadBytes 文件
 * @param fileName         文件名 默认不指定key的情况下,以文件内容的hash值作为文件名
 * @return String
 */
public String upload(byte[] uploadBytes, String fileName) {
	try {
		Response response = uploadManager.put(uploadBytes, fileName, getQiNiuToken());
		//解析上传成功的结果
		DefaultPutRet putRet = JsonMapper.getInstance().fromJson(response.bodyString(), DefaultPutRet.class);
		return qiNiuConfig.getDomainOfBucket() + "/" + putRet.key;
	} catch (QiniuException ex) {
		log.error("upload to qiniu exception: {}", ex.getMessage(), ex);
		throw new OssException(ex, "upload to qiniu exception");
	}
}
 
Example #30
Source File: QiNiuRestApi.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    //zong2() 代表华南地区
    Configuration cfg = new Configuration(Zone.zone2());

    UploadManager uploadManager = new UploadManager(cfg);

    //AccessKey的值
    String accessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";

    //SecretKey的值
    String secretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";

    //存储空间名
    String bucket = "XXXXXXXXXXX";

    //上传图片路径
    String localFilePath = "D:\\1582507567527.png";

    //在七牛云中图片的命名
    String key = "1582507567527.png";
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    try {
        Response response = uploadManager.put(localFilePath, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
    } catch (QiniuException ex) {
        Response r = ex.response;
        System.err.println(r.toString());
        try {
            System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
}