七牛云存储android客户端及java服务端代码编写
// 获取七牛云存储token @RequestMapping(value = "/qiniu_token", method = RequestMethod.POST) public @ResponseBody MessageMT qiniuToken(@RequestBody MessageMT msgEx) { ...... if (dbUser != null) { Config.ACCESS_KEY = "你的ak"; Config.SECRET_KEY = "你的sk"; Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY); String bucketName = "你的空间名称"; PutPolicy putPolicy = new PutPolicy(bucketName); int code = MTConstant.STATUS_CODE_DEFAULT; String uptoken = ""; try { code = MTConstant.STATUS_CODE_OK; uptoken = putPolicy.token(mac); } catch (AuthException e) { code = MTConstant.STATUS_CODE_ERROR; e.printStackTrace(); } catch (JSONException e) { code = MTConstant.STATUS_CODE_ERROR; e.printStackTrace(); } return new MessageMT(uptoken, code, Long.valueOf(0), ""); } else { return new MessageMT("", MTConstant.STATUS_CODE_ERROR, Long.valueOf(0), ""); } }
private final CountDownLatch signal = new CountDownLatch(1); // 数据处理 @Override protected Void doInBackground(Void... params) { publishProgress(1); try { ...... // 获取token(这里的strUrl就是服务端提供的接口url) msgObj = restTemplate.postForObject(strUrl, msgEx, MessageMT.class); publishProgress(5); // 开始上传 if ((msgObj != null) && (msgObj.getStatusCode() == IConstant.STATUS_CODE_OK)) { String uptoken = msgObj.getMsg(); String partFileName = msgObj.getParamString(); String imageFileName = Util.getMD5(userName) + "_" + partFileName + ".jpg";// 拼接文件名 UploadManager uploadManager = new UploadManager(); uploadManager.put("待上传的文件路径", imageFileName, uptoken, new UpCompletionHandler() { @Override public void complete(String key, ResponseInfo info, JSONObject response) { if (info.isOK()) { // 这里的key就是七牛返回的上传成功的文件名,其实与上面的imageFileName是一样的 msgObj.setParamString(key); } else { msgObj.setStatusCode(IConstant.STATUS_CODE_ERROR); } signal.countDown(); } }, new UploadOptions(null, null, false, new UpProgressHandler() { @Override public void progress(String key, double percent) { publishProgress(5 + (int)(percent * 85));// 更新上传进度 } }, null)); try { signal.await(60, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } ...... ...向自己的业务数据库插入返回的文件名... ...... }// if } catch (Exception e) { if (msgObj != null) { msgObj.setStatusCode(IConstant.STATUS_CODE_ERROR); } } publishProgress(100); return null; }上述代码中,MessageMT.class是我自己封装的一个类,内部定义了几个int、long、string类型变量,仅仅用于服务器与客户端传输数据,大可不必纠结其内部结构实现。顺便贴出通过服务器调用七牛api删除文件的代码片段:
// 调用七牛云存储接口,删除相关图片 public static void deleteAllImageInQiNiu(List<String> imageFileNameList) { Config.ACCESS_KEY = "你的ak"; Config.SECRET_KEY = "你的sk"; Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY); RSClient rs = new RSClient(mac); List<EntryPath> entries = new ArrayList<EntryPath>(); for (String fileName : imageFileNameList) { EntryPath entrypath = new EntryPath(); entrypath.bucket = "你的空间名称"; entrypath.key = fileName; entries.add(entrypath); } if (entries.size() > 0) { rs.batchDelete(entries); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。