/中级项目课代码/src/main/java/com/nowcoder/service/QiniuService.java

https://bitbucket.org/xiaoyang0112/sourcetree · Java · 68 lines · 49 code · 8 blank · 11 comment · 5 complexity · e0769154fc22efc679dfd9f3870ffcba MD5 · raw file

  1. package com.nowcoder.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.nowcoder.util.ToutiaoUtil;
  4. import com.qiniu.common.QiniuException;
  5. import com.qiniu.http.Response;
  6. import com.qiniu.storage.UploadManager;
  7. import com.qiniu.util.Auth;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.stereotype.Service;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import java.io.IOException;
  13. import java.util.UUID;
  14. /**
  15. * Created by nowcoder on 2016/7/7.
  16. */
  17. @Service
  18. public class QiniuService {
  19. private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);
  20. //设置好账号的ACCESS_KEY和SECRET_KEY
  21. String ACCESS_KEY = "abNXnXBIlI6viRaOeRY6Hk-zc3V-NpjLcGfYz5kD";
  22. String SECRET_KEY = "QP7Xja3FmP1Zyl-oxwQDCb7T6wCoEFKoO-0vht_5";
  23. //要上传的空间
  24. String bucketname = "nowcoder";
  25. //密钥配置
  26. Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
  27. //创建上传对象
  28. UploadManager uploadManager = new UploadManager();
  29. private static String QINIU_IMAGE_DOMAIN = "http://7xsetu.com1.z0.glb.clouddn.com/";
  30. //简单上传,使用默认策略,只需要设置上传的空间名就可以了
  31. public String getUpToken() {
  32. return auth.uploadToken(bucketname);
  33. }
  34. public String saveImage(MultipartFile file) throws IOException {
  35. try {
  36. int dotPos = file.getOriginalFilename().lastIndexOf(".");
  37. if (dotPos < 0) {
  38. return null;
  39. }
  40. String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
  41. if (!ToutiaoUtil.isFileAllowed(fileExt)) {
  42. return null;
  43. }
  44. String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
  45. //调用put方法上传
  46. Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
  47. //打印返回的信息
  48. if (res.isOK() && res.isJson()) {
  49. return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
  50. } else {
  51. logger.error("七牛异常:" + res.bodyString());
  52. return null;
  53. }
  54. } catch (QiniuException e) {
  55. // 请求失败时打印的异常的信息
  56. logger.error("七牛异常:" + e.getMessage());
  57. return null;
  58. }
  59. }
  60. }