Browse Source

文件上传相关配置

wangmiaomiao 10 months ago
parent
commit
dba93855c3

+ 27 - 15
slibra-admin/src/main/java/com/slibra/web/controller/common/UploadController.java

@@ -2,12 +2,18 @@ package com.slibra.web.controller.common;
 
 import com.slibra.common.config.QiNiuYunProperties;
 import com.slibra.common.core.domain.AjaxResult;
+import com.slibra.common.core.domain.R;
 import com.slibra.framework.web.service.QiNiuYunServiceImpl;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
+@Api(tags = "七牛云相关接口")
 @Slf4j
 @RestController
 @RequestMapping("/qiniuyun")
@@ -25,18 +31,34 @@ public class UploadController {
     }
 
 
+    @ApiOperation(value = "文件上传",httpMethod = "POST")
+    @ApiParam(name = "file",value = "要上传的文件")
+//    @ApiImplicitParam(name = "file", value = "文件上传form表单的key叫file", dataType = "multipart/form-data", dataTypeClass = FormatData.class, required = true)
     @PostMapping(value = "/upLoadImage")
-    private AjaxResult upLoadImage(@RequestParam("file") MultipartFile file) {
-        AjaxResult ajax = AjaxResult.success();
+    private R<String> upLoadImage(@RequestParam("file") MultipartFile file) {
         if (!file.isEmpty()) {
             String url = qiNiuYunService.uploadQNImg(file);
             log.info("七牛云返回的图片链接:{}", url);
-            ajax.put("url", url);
-            return ajax;
+            return R.ok(url);
         }
-        return ajax;
+        return R.fail("上传的文件不存在");
+    }
+
+
+    /*
+     * @Param
+     * @return java.lang.String
+     **/
+    @ApiOperation("删除七牛云上的文件")
+    @ApiImplicitParam(name = "fileKey", value = "上传以后接口返回的文件的名字", dataType = "String", dataTypeClass = String.class, required = true)
+    @DeleteMapping("/remove")
+    public R<Void> removeFile(@RequestParam String fileKey){
+        qiNiuYunService.removeFile(qiNiuYunProperties.getBucketName(),fileKey);
+        return R.ok(null, "删除成功");
     }
 
+
+
     /**
      * 内服方法调用
      * @param fileKey
@@ -50,15 +72,5 @@ public class UploadController {
         return ajax;
     }
 
-    /*
-     * @Param
-     * @return java.lang.String
-     **/
-    @DeleteMapping("/remove")
-    public AjaxResult removeFile(@RequestParam String fileKey){
-        qiNiuYunService.removeFile(qiNiuYunProperties.getBucketName(),fileKey);
-        return AjaxResult.success("删除成功");
-    }
-
 }
 

+ 5 - 0
slibra-common/src/main/java/com/slibra/common/constant/CacheConstants.java

@@ -47,4 +47,9 @@ public class CacheConstants
     //自定义Redis常量
     public static final String REDIS_KEY_SMSLOGIN_SMSCODE = "redis_key_smslogin_smscode:";
     public static final Integer REDIS_EXPIRATION_SMSLOGIN_SMSCODE = 10;
+
+    //七牛云上传token的key
+    public static final String QINIUYUN_UPLOAD_KEY = "qiniuyun_upload_key";
+    public static final Integer QINIUYUN_UPLOAD_KEY_TIME = 3500;//3500秒 小于3600
+
 }

+ 65 - 15
slibra-framework/src/main/java/com/slibra/framework/web/service/QiNiuYunServiceImpl.java

@@ -1,5 +1,6 @@
 package com.slibra.framework.web.service;
 
+import com.alibaba.fastjson2.JSON;
 import com.qiniu.common.QiniuException;
 import com.qiniu.common.Zone;
 import com.qiniu.http.Response;
@@ -9,24 +10,34 @@ import com.qiniu.storage.UploadManager;
 import com.qiniu.util.Auth;
 import com.slibra.common.config.QiNiuYunProperties;
 import com.slibra.common.constant.MyConstants;
+import com.slibra.common.core.redis.RedisCache;
+import com.slibra.common.utils.StringUtils;
 import com.slibra.common.utils.third.StringUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
+import java.util.concurrent.TimeUnit;
 
+import static com.slibra.common.constant.CacheConstants.QINIUYUN_UPLOAD_KEY;
+import static com.slibra.common.constant.CacheConstants.QINIUYUN_UPLOAD_KEY_TIME;
 
 
 @Service
 @Slf4j
+//@DependsOn("redisCache")
 public class QiNiuYunServiceImpl {
 
     @Autowired
     private QiNiuYunProperties qiNiuYunProperties;
 
+    @Autowired
+    private RedisCache redisCache;
+
     // 七牛文件上传管理器
     private UploadManager uploadManager;
     //上传的token
@@ -48,7 +59,8 @@ public class QiNiuYunServiceImpl {
         auth = Auth.create(qiNiuYunProperties.getAccessKey(), qiNiuYunProperties.getSecretKey());
         // 根据命名空间生成的上传token
         bucketManager = new BucketManager(auth, new Configuration(Zone.zone1()));
-        token = auth.uploadToken(qiNiuYunProperties.getBucketName());
+//        token = auth.uploadToken(qiNiuYunProperties.getBucketName());
+//        redisCache.setCacheObject(QINIUYUN_UPLOAD_KEY, token, QINIUYUN_UPLOAD_KEY_TIME, TimeUnit.SECONDS);
     }
 
     /*
@@ -57,30 +69,51 @@ public class QiNiuYunServiceImpl {
      * @return java.lang.String
      **/
     public String uploadQNImg(MultipartFile file) {
+        FileInputStream inputStream = null;
         try {
             // 获取文件的名称
             String fileName = file.getOriginalFilename();
-
+//            log.info("获取到的文件的名字是{}", fileName);
             // 使用工具类根据上传文件生成唯一图片名称
             String imgName = MyConstants.QI_NIU_YUN_UPLOAD_URL + StringUtil.getRandomImgName(fileName);
-
-            FileInputStream inputStream = (FileInputStream) file.getInputStream();
+//            log.info("处理以后到的文件的名字是{}", imgName);
+            inputStream = (FileInputStream) file.getInputStream();
             // 上传图片文件
+            //token默认是3600s Redis缓存处理
+            token = redisCache.getCacheObject(QINIUYUN_UPLOAD_KEY);
+            if(StringUtils.isBlank(token)){
+                log.info("七牛云缓存的token过期了或者是第一次初始化");
+                token = auth.uploadToken(qiNiuYunProperties.getBucketName());
+                redisCache.setCacheObject(QINIUYUN_UPLOAD_KEY, token, QINIUYUN_UPLOAD_KEY_TIME, TimeUnit.SECONDS);
+            }
             Response res = uploadManager.put(inputStream, imgName, token, null, null);
+//            log.info("上传接口返回的结果是{}", JSON.toJSONString(res));
             if (!res.isOK()) {
-                throw new RuntimeException("上传七牛出错:" + res.toString());
+                throw new RuntimeException("上传七牛出错,返回结果是:" + JSON.toJSONString(res));
             }
             // 解析上传成功的结果
 //            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
 
             // 直接返回外链地址
-            return getPrivateFile(imgName);
+            return getPublicName(imgName);
         } catch (QiniuException e) {
-            e.printStackTrace();
-        } catch (Exception e) {
-            e.printStackTrace();
+            //这里有个bug  e.printStackTrace() 不打印异常信息,假如遇到token过期了,但是不会抛出异常
+            log.error("上次异常,异常信息为{}", e.getMessage());
+            throw new RuntimeException(e);
+        } catch (IOException e) {
+            log.error("上次异常,异常信息为{}", e.getMessage());
+            throw new RuntimeException(e);
+        } finally {
+            try {
+                inputStream.close();
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
         }
-        return "";
+    }
+
+    private String getPublicName(String imgName) {
+        return String.format("%s/%s", this.qiNiuYunProperties.getUrl(), imgName);
     }
 
     /**
@@ -88,19 +121,22 @@ public class QiNiuYunServiceImpl {
      *
      * @param fileKey
      * @return
+     * 2023年12月8日13:50:33 做为公共链接返回
      */
     public String getPrivateFile(String fileKey) {
         String encodedFileName = null;
-        String finalUrl = null;
+//        String finalUrl = null;
         try {
             encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
-            String publicUrl = String.format("%s/%s", this.qiNiuYunProperties.getUrl(), encodedFileName);
-            long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
-            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
+            return String.format("%s/%s", this.qiNiuYunProperties.getUrl(), encodedFileName);
+//            String publicUrl = String.format("%s/%s", this.qiNiuYunProperties.getUrl(), encodedFileName);
+//            long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
+//            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }
-        return finalUrl;
+//        return finalUrl;
+        return "";
     }
 
     /*
@@ -117,4 +153,18 @@ public class QiNiuYunServiceImpl {
         return true;
     }
 
+
+    public static void main(String[] args) throws UnsupportedEncodingException {
+        String str = URLEncoder.encode("abc/ddd", "utf-8").replace("+", "%20");
+        System.out.println(String.format("%s/%s", "https://static.fuxicarbon.com", str));
+        System.out.println(String.format("%s/%s", "https://static.fuxicarbon.com", "abc/ddd"));
+
+        try {
+            int i = 5/0;
+        } catch (Exception e) {
+//            throw new RuntimeException(e);
+            e.printStackTrace();
+        }
+    }
+
 }