Java Code Examples for com.qiniu.storage.UploadManager#put()

The following examples show how to use com.qiniu.storage.UploadManager#put() . 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: 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 3
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 4
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 5
Source File: FileUploadImpl.java    From uexam-mysql with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream, long size, String extName) {
    QnConfig qnConfig = systemConfig.getQn();
    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(qnConfig.getAccessKey(), qnConfig.getSecretKey());
    String upToken = auth.uploadToken(qnConfig.getBucket());
    try {
        Response response = uploadManager.put(inputStream, null, upToken, null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return qnConfig.getUrl() + "/" + putRet.key;
    } catch (QiniuException ex) {
        logger.error(ex.getMessage(), ex);
    }
    return null;
}
 
Example 6
Source File: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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
        }
    }
}
 
Example 18
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 19
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);
}
 
Example 20
Source File: QiNiuServiceImpl.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
@Override
//    @CacheEvict(allEntries = true)
    @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(qiniuContentService.getOne(new QueryWrapper<QiniuContent>().eq("name",key)) != null) {
                key = QiNiuUtil.getKey(key);
            }
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果

            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

            QiniuContent content = qiniuContentService.getOne(new QueryWrapper<QiniuContent>().eq("name",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.setName(FileUtil.getFileNameNoEx(putRet.key));
                qiniuContent.setUrl(qiniuConfig.getHost()+"/"+putRet.key);
                qiniuContent.setSize(FileUtil.getSize(Integer.parseInt(file.getSize()+"")));
                qiniuContentService.save(qiniuContent);
                return qiniuContent;
            }
            return content;
        } catch (Exception e) {
           throw new BadRequestException(e.getMessage());
        }
    }