七牛云存储_入门及使用
来源:互联网 发布:php 下载文件 编辑:程序博客网 时间:2024/06/05 19:05
入门建议
简单介绍
http://blog.csdn.net/silence2015/article/details/50528438
官方API
文件上传 https://developer.qiniu.com/kodo/sdk/1239/java#5
文件下载 https://developer.qiniu.com/kodo/sdk/1239/java#6
实际开发
详细pom配置
https://developer.qiniu.com/kodo/sdk/1239/java#3
代码实现
常量类
/** * 定义七牛文件上传下载的常量类 * @Description * @version 1.0.0 * @Author create by ZengWei on 2017-12-25 * */public class QiniuFileServerConstants { //七牛服务器秘钥accesskey public static final String ACCESSKEY = "xxx"; //七牛服务器秘钥secretkey public static final String SECRETKEY = "xxx"; //七牛服务器中对应的存储空间名字 public static final String BUCKET = "xxx"; //测试的域名地址 public static final String DOMIAN_NAME = "xxx"; /** * 定义七牛服务器存储的区域 * 华东zone0()、华北zone1()、华南zone2()、北美zoneNa0() */ public static final Zone ZONE_AREA = Zone.zone0(); public static void download(String targetURL) { try { URL url = new URL(targetURL); //创建读取url流对象 InputStream in = url.openStream(); File dir = new File("D:\\qiniu_download"); String contractName = "七牛下载"; String fileName = contractName +"_"+ String.valueOf(System.currentTimeMillis()) +".pdf"; File file = new File(dir,fileName); FileOutputStream out = new FileOutputStream(file); Streams.copy(in, out, true); } catch (IOException e) { e.printStackTrace(); } }}
核心代码
/** * 将pdf文件上传到bucket */ public static String upload(String localFilePath) { //1.构建一个带指定区域对象的配置类 Configuration cfg = new Configuration(QiniuFileServerConstants.ZONE_AREA); UploadManager manage = new UploadManager(cfg); //生成上传凭证,然后准备上传 //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = null; //1.进行身份认证 Auth upAuth = Auth.create(QiniuFileServerConstants.ACCESSKEY, QiniuFileServerConstants.SECRETKEY); String upToken = upAuth.uploadToken(QiniuFileServerConstants.BUCKET); try { Response response = manage.put(localFilePath, key, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return putRet.key; } catch (QiniuException e) { Response r = e.response; logger.info("七牛上传文件失败!" + r.toString()); } return ""; } public static String getURL(String key) { //1.构建公开空间访问链接 try { String url = ""; url = "http://" + QiniuFileServerConstants.DOMIAN_NAME + "/" + key; //2.进行私有授权签名 Auth auth = Auth.create(QiniuFileServerConstants.ACCESSKEY, QiniuFileServerConstants.SECRETKEY); //自定义链接过期时间(单位s) long expireInSeconds = 3600;//1小时 //生成下载链接 String finalUrl = auth.privateDownloadUrl(url, expireInSeconds); System.out.println(finalUrl); return finalUrl; } catch (Exception e) { logger.error(e.getMessage(), e); return ""; } }
开发总结
在研发团队引入第三方技术时,最好先熟悉其功能范围,然后直接从官方API入手(如果没有,再查找其它开发者的相关资料,对于官方API不要做太深入的了解,自己开发中功能用到哪一块,就直接看哪一块就好了。
看得太宽太泛,首先自己容易晕车,再者影响工作进度,等日后使用过程中,再慢慢熟悉它功能所能做的其它事情),然后直接写测试demo,并调试,这样能够较快地将技术应用到项目当中。
阅读全文