瀏覽代碼

文件直接上传oss

wuweihao 2 年之前
父節點
當前提交
eaa70e0cbb

+ 1 - 0
720yun_fd_manage/gis_application/src/main/resources/application-sit.properties

@@ -83,6 +83,7 @@ oss.point=http://oss-cn-shenzhen-internal.aliyuncs.com
 oss.key=LTAIUrvuHqj8pvry
 oss.secrecy=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
 oss.bucket=oss-xiaoan
+# \u4E0A\u4F20\u6587\u4EF6\u4FDD\u5B58\u4F4D\u7F6E\u7C7B\u578B
 oss.type=oss
 oss.file.path=${project.name}/
 oss.domain=https://ossxiaoan.4dage.com/

+ 1 - 1
720yun_fd_manage/gis_application/src/main/resources/application.properties

@@ -20,7 +20,7 @@ spring.servlet.multipart.max-file-size=256MB
 spring.servlet.multipart.max-request-size=256MB
 
 # 2021-3-9 POST\u8BF7\u6C42\u9ED8\u8BA4\u6700\u59272M\uFF0C -1\uFF1A\u4E0D\u9650\u5236
-server.tomcat.max-http-post-size=100MB
+#server.tomcat.max-http-post-size=100MB
 #form\u8868\u5355\u957F\u5EA6
 server.tomcat.max-http-form-post-size=100MB
 

+ 5 - 3
720yun_fd_manage/gis_common/src/main/java/com/gis/common/constant/ErrorEnum.java

@@ -23,11 +23,11 @@ public enum ErrorEnum {
 
     // 300X -> 系统类
     FAILURE_SYS_3001(3001, "对象不存在"),
+    FAILURE_SYS_3011(3011, "没有操作权限")
 
     // 301X -> 权限问题类
-//    FAILURE_SYS_3010(3010, "Token为空"),
-    FAILURE_SYS_3011(3011, "没有操作权限"),
-//    FAILURE_CODE_3001(3001, "缺少必要参数"),
+,    //    FAILURE_SYS_3010(3010, "Token为空"),
+
 //    FAILURE_CODE_3002(3002, "访问异常!"),
 //    FAILURE_CODE_3003(3003, "非法访问!"),
 //    FAILURE_CODE_3004(3004, "用户未登录"),
@@ -55,6 +55,8 @@ public enum ErrorEnum {
     FAILURE_CODE_3025(3025, "上传失败"),
     FAILURE_CODE_3026(3026, "非法文件, 图片没有像素"),
 
+    FAILURE_CODE_3031(3031, "缺少必要参数"),
+
 
     // 31XX -> 自定义异常
     FAILURE_CODE_3101(3101, "素材已经被引用, 不能删除"),

+ 20 - 0
720yun_fd_manage/gis_domain/src/main/java/com/gis/domain/dto/FileSceneDto.java

@@ -0,0 +1,20 @@
+package com.gis.domain.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by owen on 2023/1/31 0023 16:39
+ */
+@Data
+public class FileSceneDto {
+
+
+
+    @ApiModelProperty(value = "文件", required = true)
+    private MultipartFile file;
+
+    @ApiModelProperty(value = "场景码", required = true)
+    private String sceneCode;
+}

+ 67 - 9
720yun_fd_manage/gis_oss/src/main/java/com/gis/oss/util/AliYunOssUtil.java

@@ -1,5 +1,7 @@
 package com.gis.oss.util;
 
+import cn.hutool.core.collection.CollUtil;
+import com.aliyun.oss.ClientException;
 import com.aliyun.oss.OSSClient;
 import com.aliyun.oss.model.*;
 import com.gis.common.constant.ConfigConstant;
@@ -7,17 +9,13 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.io.*;
+import java.net.URLDecoder;
+import java.util.*;
 
 /**
  * 阿里云oss工具类
+ * 参考:https://help.aliyun.com/document_detail/84842.htm?spm=a2c4g.11186623.0.0.606a282dA00Gt3#t22290.html
  */
 @Slf4j
 @Component
@@ -137,7 +135,7 @@ public class AliYunOssUtil {
      * @param prefix 图片路径
      * @return
      */
-    public  int deleteFile(String prefix) {
+    public  int deleteDir(String prefix) {
         OSSClient ossClient = init();
         ObjectListing objectListing = ossClient.listObjects(configConstant.ossBucket, prefix);
         List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
@@ -151,6 +149,66 @@ public class AliYunOssUtil {
         return sums.size();
     }
 
+    /**
+     * 2023-1-31
+     * 删除单个文件, 不能删除目录
+     * @param ossKey 填写文件完整路径。文件完整路径中不能包含Bucket名称。
+     * 同时也不能以“/”或者“\”开头。
+     */
+    public void deleteFile(String ossKey) {
+        OSSClient ossClient = init();
+        try {
+            ossClient.deleteObject(configConstant.ossBucket, ossKey);
+            log.info("删除oss文件完成:{}", ossKey);
+        } catch (ClientException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+
+    public void deleteOssFile(String prefix){
+        int maxKeys = 200;
+        OSSClient ossClient = init();
+        try {
+
+            String nextMarker = null;
+            ObjectListing objectListing;
+
+            do {
+                objectListing = ossClient.listObjects(new ListObjectsRequest(configConstant.ossBucket).withPrefix(prefix).withMarker(nextMarker).withMaxKeys(maxKeys));
+                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
+                if (CollUtil.isEmpty(sums)) {
+                    return;
+                }
+                List<String> keys = new ArrayList<>();
+                for (OSSObjectSummary sum : sums) {
+                    keys.add(sum.getKey());
+                }
+                DeleteObjectsRequest deleteObjectsRequest =
+                        new DeleteObjectsRequest(configConstant.ossBucket).withKeys(keys).withEncodingType("url");
+                DeleteObjectsResult deleteObjectsResult = ossClient
+                        .deleteObjects(deleteObjectsRequest);
+                List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
+                try {
+                    for (String deletedObject : deletedObjects) {
+                        String decode = URLDecoder.decode(deletedObject, "UTF-8");
+                        log.info("删除oss文件:{}", decode);
+                    }
+                } catch (UnsupportedEncodingException e) {
+                    e.printStackTrace();
+                }
+
+            }while (objectListing.isTruncated());
+        }catch (Exception  e){
+            e.printStackTrace();
+        }finally {
+            if(ossClient != null){
+                ossClient.shutdown();
+            }
+        }
+    }
+
     public  void main(String[] args) throws IOException {
 
         HashMap<String, String> map = new HashMap<>();

+ 19 - 72
720yun_fd_manage/gis_oss/src/main/java/com/gis/oss/util/FileAndOssUtil.java

@@ -194,20 +194,23 @@ public class FileAndOssUtil {
 //			case "local":FileUtil.del(key1);  break;
 //		}
 //	}
-//
-//	/**
-//	 * 删除目录或者文件
-//	 * @param prefix
-//	 * @return
-//	 */
-//	public int deleteFile(String prefix){
-//		switch (type){
-//			case "oss":deleteOssFile(prefix); break;
+
+	/**
+	 * 删除目录或者文件
+	 * @param prefix
+	 * @return
+	 */
+	public int deleteFile(String prefix){
+		if (StringUtils.isBlank(prefix)){
+			return 0;
+		}
+		switch (type){
+			case "oss":aliyunOssUtil.deleteFile(prefix); break;
 //			case "aws": deleteAwsFile(prefix); break;
-//			case "local":FileUtil.del(prefix);  break;
-//		}
-//		return 1;
-//	}
+			case "local":FileUtil.del(prefix);  break;
+		}
+		return 1;
+	}
 //
 //	public void deleteOss(String objectName){
 //		OSSClient ossClient = new OSSClient(point, key, secrey);
@@ -221,65 +224,9 @@ public class FileAndOssUtil {
 //			}
 //		}
 //	}
-//
-//	public void deleteOssFile(String prefix){
-//		int maxKeys = 200;
-//		OSSClient ossClient = new OSSClient(point, key, secrey);
-//		try {
-//
-//			String nextMarker = null;
-//			ObjectListing objectListing;
-//
-//			do {
-//				objectListing = ossClient.listObjects(new ListObjectsRequest(this.bucket).withPrefix(prefix).withMarker(nextMarker).withMaxKeys(maxKeys));
-//				List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
-//				if (CollUtil.isEmpty(sums)) {
-//					return;
-//				}
-//				List<String> keys = new ArrayList<>();
-//				for (OSSObjectSummary sum : sums) {
-//					keys.add(sum.getKey());
-//				}
-//				DeleteObjectsRequest deleteObjectsRequest =
-//					new DeleteObjectsRequest(bucket).withKeys(keys).withEncodingType("url");
-//				DeleteObjectsResult deleteObjectsResult = ossClient
-//					.deleteObjects(deleteObjectsRequest);
-//				List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
-//				try {
-//					for (String deletedObject : deletedObjects) {
-//						String decode = URLDecoder.decode(deletedObject, "UTF-8");
-//						log.info("删除oss文件:{}", decode);
-//					}
-//				} catch (UnsupportedEncodingException e) {
-//					e.printStackTrace();
-//				}
-//
-////				ListUtil.page(keys, 100, subKeys -> {
-////					DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket)
-////						.withKeys(
-////							subKeys).withEncodingType("url");
-////					DeleteObjectsResult deleteObjectsResult = ossClient
-////						.deleteObjects(deleteObjectsRequest);
-////					List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
-////					try {
-////						for (String deletedObject : deletedObjects) {
-////							String decode = URLDecoder.decode(deletedObject, "UTF-8");
-////							log.info("删除oss文件:{}", decode);
-////						}
-////					} catch (UnsupportedEncodingException e) {
-////						e.printStackTrace();
-////					}
-////				});
-//			}while (objectListing.isTruncated());
-//		}catch (Exception  e){
-//			e.printStackTrace();
-//		}finally {
-//			if(ossClient != null){
-//				ossClient.shutdown();
-//			}
-//		}
-//	}
-//
+
+
+
 //	private void deleteAwsFile(String prefix){
 //
 //		int maxKeys = 200;

+ 30 - 1
720yun_fd_manage/gis_oss/src/main/java/com/gis/oss/util/FileUtils.java

@@ -65,6 +65,35 @@ public class FileUtils {
 
     }
 
+
+    /**
+     * 重命名文件
+     * @param file
+     * @param isPinYinRename
+     * @return
+     */
+    public String rename(MultipartFile file, boolean isPinYinRename){
+        // 检查非法文件上传
+        boolean checkFile = checkFile(file);
+        if (!checkFile) {
+            throw new BaseRuntimeException("上传文件格式有误, 请重新上传");
+        }
+
+
+        // 文件目录
+        String fileName = file.getOriginalFilename();
+        String newName;
+        if (isPinYinRename){
+            newName = RegexUtil.getPinyinName(fileName);
+        } else {
+            String suffix = StringUtils.substringAfterLast(fileName, ".");
+            String time = DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS");
+            newName =  time + ATOMIC_INTEGER.incrementAndGet() + "." + suffix;
+        }
+
+        return "/" + newName;
+    }
+
     /**
      *
      * @param file
@@ -542,7 +571,7 @@ public class FileUtils {
 
     public static boolean checkFile(MultipartFile file) {
         //设置允许上传文件类型
-        String suffixList = ".jpg,.gif,.png,.ico,.bmp,.jpeg,.zip,.zp,.rar,.mp3,.mp4,.avi,.mov";
+        String suffixList = ".jpg,.gif,.png,.ico,.bmp,.jpeg,.zip,.zp,.rar,.mp3,.mp4,.avi,.mov,.pdf";
         // 获取文件后缀
         if(file == null){
             log.info("文件流为空不可上传");

+ 5 - 4
720yun_fd_manage/gis_service/src/main/java/com/gis/service/WorkService.java

@@ -2,10 +2,7 @@ package com.gis.service;
 
 
 import com.gis.common.util.Result;
-import com.gis.domain.dto.AgePageDto;
-import com.gis.domain.dto.PageDto;
-import com.gis.domain.dto.SomeDataDto;
-import com.gis.domain.dto.WorkDto;
+import com.gis.domain.dto.*;
 import com.gis.domain.entity.WorkEntity;
 import com.gis.domain.vo.ReportWorkVo;
 import org.springframework.web.multipart.MultipartFile;
@@ -49,4 +46,8 @@ public interface WorkService extends IBaseService<WorkEntity, String> {
     List<WorkEntity> getUserWork();
 
     List<ReportWorkVo> countByType(LocalDate today);
+
+    Result uploadHot(FileSceneDto file);
+
+    Result delOss(String ossPath);
 }

+ 37 - 4
720yun_fd_manage/gis_service/src/main/java/com/gis/service/impl/WorkServiceImpl.java

@@ -1,5 +1,6 @@
 package com.gis.service.impl;
 
+import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSONArray;
@@ -9,10 +10,7 @@ import com.gis.common.constant.ErrorEnum;
 import com.gis.common.constant.RedisConstant;
 import com.gis.common.exception.BaseRuntimeException;
 import com.gis.common.util.*;
-import com.gis.domain.dto.AgePageDto;
-import com.gis.domain.dto.PageDto;
-import com.gis.domain.dto.SomeDataDto;
-import com.gis.domain.dto.WorkDto;
+import com.gis.domain.dto.*;
 import com.gis.domain.entity.FodderEntity;
 import com.gis.domain.entity.WorkEntity;
 import com.gis.domain.vo.ReportWorkVo;
@@ -321,6 +319,41 @@ public class WorkServiceImpl extends IBaseStrServiceImpl<WorkEntity, String> imp
         return voList;
     }
 
+    @Override
+    public Result uploadHot(FileSceneDto param) {
+
+        // 缩略图
+        String sceneCode = param.getSceneCode();
+        BaseRuntimeException.isBlank(sceneCode,ErrorEnum.FAILURE_CODE_3031.code(), "场景码不能为空");
+
+        MultipartFile file = param.getFile();
+        // 检查非法文件上传
+        String rename = fileUtils.rename(file, false);
+        String ossKey = configConstant.ossBasePath + sceneCode + "/hot" + rename;
+        log.info("保存oss位置:{}", ossKey);
+
+        Object urlPath = configConstant.ossDomain + ossKey;
+
+        try {
+            fileAndOssUtil.upload(file.getBytes(), ossKey);
+            return Result.success(urlPath);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        return Result.failure("上传失败");
+
+    }
+
+    @Override
+    public Result delOss(String ossPath) {
+        if (StrUtil.isBlank(ossPath)){
+            return Result.success();
+        }
+
+        fileAndOssUtil.deleteFile(ossPath);
+        return Result.success();
+    }
 
 
     @Override

+ 1 - 34
720yun_fd_manage/gis_web/src/main/java/com/gis/web/controller/FodderController.java

@@ -47,28 +47,7 @@ public class FodderController extends BaseController {
     }
 
 
-    /**
-     * 2022-12--6 旧接口停用
-     * @param file
-     * @param type
-     * @param tempId
-     * @return
-     */
-//    @ApiOperation(value = "上传素材", notes = "type:类型, 全景图:pano, 图片:image, 音频:audio, 视频:video, temId: 前端临时Id")
-//    @PostMapping("upload/{type}/{tempId}")
-//    public Result upload(MultipartFile file, @PathVariable String type, @PathVariable String tempId) {
-//
-//        if (file == null) {
-//            log.error("文件不能为空");
-//            return Result.failure(ErrorEnum.FAILURE_CODE_3020.code(),"文件不能为空");
-//        }
-//        FodderUploadDto dto = new FodderUploadDto();
-//        dto.setFile(file);
-//        dto.setTemId(tempId);
-//        dto.setType(type);
-//        dto.setDirId(1L); // 默认跟目录
-//        return fodderService.upload(dto);
-//    }
+
 
 
     /**
@@ -82,18 +61,6 @@ public class FodderController extends BaseController {
     }
 
 
-//    /**
-//     *  2022-12--6 旧接口停用
-//     *  2021-04-30
-//     *  目前只返回计算成功的数据
-//     * @param param
-//     * @return
-//     */
-//    @ApiOperation(value = "列表", position = 1)
-//    @PostMapping("list")
-//    public Result<FodderEntity> list(@RequestBody FodderPageDto param) {
-//        return fodderService.search(param);
-//    }
 
 
     @ApiOperation(value = "修改", position = 1)

+ 25 - 0
720yun_fd_manage/gis_web/src/main/java/com/gis/web/controller/WorkController.java

@@ -103,6 +103,8 @@ public class WorkController extends BaseController {
     }
 
 
+
+
     @ApiOperation(value = "检查作品token是否有效" , position = 3)
     @GetMapping("checkToken/{workId}")
     public Result checkToken(@PathVariable String workId) {
@@ -145,6 +147,29 @@ public class WorkController extends BaseController {
     }
 
 
+    /**
+     * 2023-1-31
+     * 附件不需要存素材库
+     * 主要用于热点上传
+     * @return
+     */
+    @ApiOperation(value = "v1.3-上传附件")
+    @PostMapping("/uploadHot")
+    public Result uploadHot(FileSceneDto param) {
+        return workService.uploadHot(param);
+    }
+
+
+    /**
+     * 相对地址
+     * @param ossPath 不能以“/”或者“\”开头。
+     * @return
+     */
+    @ApiOperation(value = "v1.3-删除oss文件", notes = "不能以“/”或者“\\”开头, 相对路径")
+    @GetMapping("/delOss")
+    public Result delOss(String ossPath) {
+        return workService.delOss(ossPath);
+    }
 
 
 }