com.qiniu.storage.UploadManager Java Examples

The following examples show how to use com.qiniu.storage.UploadManager. 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: QiniuOssClient.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 如果是第一次使用, ossClient == null
 */
private static void init() {
    QiniuOssState qiniuOssState = MikPersistenComponent.getInstance().getState().getQiniuOssState();
    domain = qiniuOssState.getEndpoint();
    String accessKey = qiniuOssState.getAccessKey();
    String secretKey = DES.decrypt(qiniuOssState.getAccessSecretKey(), MikState.QINIU);
    String bucketName = qiniuOssState.getBucketName();

    Optional<ZoneEnum> zone = EnumsUtils.getEnumObject(ZoneEnum.class, e -> e.getIndex() == qiniuOssState.getZoneIndex());
    try {
        Configuration cfg = new Configuration(zone.orElse(ZoneEnum.EAST_CHINA).zone);
        ossClient = new UploadManager(cfg);
        buildToken(Auth.create(accessKey, secretKey), bucketName);
    } catch (Exception ignored) {
    }
}
 
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: FileServiceQiNiuYun.java    From smart-admin with MIT License 6 votes vote down vote up
@Override
public ResponseDTO<String> getFileUrl(String path) {
    OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
    try {
        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 encodedFileName = URLEncoder.encode(path, "utf-8");
        String domainOfBucket = ossConfig.getEndpoint();
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = ossConfig.getAccessKeyId();
        String secretKey = ossConfig.getAccessKeySecret();
        Auth auth = Auth.create(accessKey, secretKey);
        //1小时,可以自定义链接过期时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return ResponseDTO.succData(finalUrl);
    } catch (Exception e) {
        log.error("QINIU getFileUrl ERROR : {}", e);
    }
    return ResponseDTO.wrap(FileResponseCodeConst.URL_ERROR);
}
 
Example #5
Source File: QiniuProvider.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public QiniuProvider(String urlprefix, String bucketName, String accessKey, String secretKey,boolean isPrivate) {
	
	Validate.notBlank(bucketName, "[bucketName] not defined");
	Validate.notBlank(accessKey, "[accessKey] not defined");
	Validate.notBlank(secretKey, "[secretKey] not defined");
	Validate.notBlank(urlprefix, "[urlprefix] not defined");
	
	this.urlprefix = urlprefix.endsWith(DIR_SPLITER) ? urlprefix : urlprefix + DIR_SPLITER;
	this.bucketName = bucketName;
	auth = Auth.create(accessKey, secretKey);

	Zone region = Zone.autoZone();
	Configuration c = new Configuration(region);
	uploadManager = new UploadManager(c);
	bucketManager = new BucketManager(auth,c);
	
	this.isPrivate = isPrivate;
	this.host = StringUtils.remove(urlprefix,"/").split(":")[1];
}
 
Example #6
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 #7
Source File: QiNiuUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Configuration cfg = new Configuration(Zone.zone0());
    cfg.connectTimeout=5000;
    cfg.readTimeout=5000;
    cfg.writeTimeout=2000;
    auth = Auth.create(accessKey, secretKey);
    uploadManager = new UploadManager(cfg);
    // 实例化一个BucketManager对象
    bucketManager = new BucketManager(auth, cfg);

    new Thread() {
        public void run() {
            deleteBlockingDequeImage();
        }
    }.start();
}
 
Example #8
Source File: QiniuFileProvider.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 上传
 *
 * @param path  文件路径
 * @param bytes 文件流
 * @return 上传后的文件夹名称
 */
@Override
public String upload(String path, byte[] bytes) throws IOException {
    Auth auth = Auth.create(ConfigUtils.getQiniuAccessKey(), ConfigUtils.getQiniuSecretKey());
    UploadManager uploadManager = new UploadManager();
    try {
        String token = auth.uploadToken(ConfigUtils.getBucketURL(), path, 3600, new StringMap().put("insertOnly", 0));
        Response res = uploadManager.put(bytes, path, token);
        String result = res.bodyString();
        logger.debug("qiniuUpload:" + result);
        if (result.contains("\"key\"")) {
            return path;
        }
        throw new IOException(result);
    } catch (QiniuException e) {
        Response r = e.response;
        throw new IOException(r.bodyString());
    }
}
 
Example #9
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 #10
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 #11
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 6 votes vote down vote up
/**
 * 上传base64位的图片
 * @param base64
 * @return
 */
public static String uploadBase64(String base64,String name) {
	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),filePath;

	byte[] data = Base64.decodeBase64(base64);
	try {
		uploadManager.put(data,name,token);
	} catch (IOException e) {
		e.printStackTrace();
	}
	filePath = path+name;
	return filePath;
}
 
Example #12
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 #13
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 #14
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 #15
Source File: FileService.java    From ml-blog with MIT License 5 votes vote down vote up
/**
 * 文件上传
 * @param inputStream
 * @param filename
 * @return
 */
public Response upload(InputStream inputStream, String filename) throws GlobalException{

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

    try {

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

        return response;
    } catch (QiniuException ex) {
        Response r = ex.response;
        log.error("文件上传异常:",r.toString());
        throw new GlobalException(500, ex.toString());
    }
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
Source File: FileService.java    From ml-blog with MIT License 5 votes vote down vote up
/**
 * 创建七牛云相关组件
 */
private void createQiniuComponent() {
    Configuration cfg = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(commonMap.get("qn_accessKey").toString(), commonMap.get("qn_secretKey").toString());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    String upToken = auth.uploadToken(commonMap.get("qn_bucket").toString());
    commonMap.put("uploadManager",uploadManager);
    commonMap.put("bucketManager",bucketManager);
    commonMap.put("upToken",upToken);
}
 
Example #21
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 #22
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;
}
 
Example #23
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 #24
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 #25
Source File: QNUploader.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
public UploadInfo upload(String qq, File file, String ak, String sk,
        String bucket, Zone zone) throws Exception {
        
    // 默认不指定key的情况下,以文件内容的hash值作为文件名
    String key = String.format("%s/%s", qq, file.getName());
    AuthInfo authInfo = getToken(qq, ak, sk, bucket, key);
    System.out.println(authInfo);
    if (authInfo.limit > 0 && file.length() > authInfo.limit) {
        throw new RuntimeException("今日上传流量不足,剩余流量:" + authInfo.limit);
    }
    // 构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(
            zone == null ? Zone.autoZone() : zone);
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    com.qiniu.http.Response response = uploadManager
            .put(file.getAbsolutePath(), key, authInfo.token);
    if (!response.isOK()) {
        throw new RuntimeException(
                response.error + "(code=" + response.statusCode + ")");
    }
    // 解析上传成功的结果
    UploadInfo putRet = new Gson().fromJson(response.bodyString(),
            UploadInfo.class);
    if (authInfo.domain != null && !authInfo.domain.isEmpty()) {
        putRet.domain = authInfo.domain;
    }
    if (authInfo.limit > 0) {
        callback(qq, putRet);
    }
    return putRet;
}
 
Example #26
Source File: QiniuProvider.java    From azeroth with Apache License 2.0 5 votes vote down vote up
public QiniuProvider(String urlprefix, String bucketName, String accessKey, String secretKey) {
    this.urlprefix = urlprefix.endsWith(DIR_SPLITER) ? urlprefix : urlprefix + DIR_SPLITER;
    this.bucketName = bucketName;
    auth = Auth.create(accessKey, secretKey);

    Zone z = Zone.autoZone();
    Configuration c = new Configuration(z);
    uploadManager = new UploadManager(c);
    bucketManager = new BucketManager(auth, c);
}
 
Example #27
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 #28
Source File: QiniuOSSTest.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    File file = new File("F:/data/a_2.jpg");
    byte[] bytes = ImageUtils.screenshot(file, 360, 200);
    final String key = "/static" + UpYunUtils.md5(bytes) + ".jpg";

    Zone z = Zone.autoZone();
    Configuration configuration = new Configuration(z);

    final Auth auth = Auth.create(accessKey, secretKey);
    final String upToken = auth.uploadToken(bucket, key);
    try {
        final UploadManager uploadManager = new UploadManager(configuration);
        final Response response = uploadManager.put(bytes, key, upToken);
        System.out.println(response.bodyString());
        System.out.println(response.isOK());
    } catch (QiniuException e) {
        final Response r = e.response;
        System.err.println(r.toString());
        try {
            System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
            //ignore
        }
    }
    String filePath = domain.trim()+ key + ".jpg";
    System.out.println(filePath);
}
 
Example #29
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 #30
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);
}