Jelajahi Sumber

修改文件目录

houweiyu 5 tahun lalu
induk
melakukan
8dadeff4fa

+ 1 - 1
fdkanfang-application/src/main/resources/application-prod.properties

@@ -86,7 +86,7 @@ sms.common.sign=
 admin.email.account=service@4dage.com
 
 
-oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.point=http://oss-cn-shenzhen-internal.aliyuncs.com
 oss.key=LTAIUrvuHqj8pvry
 oss.secrey=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
 oss.bucket=4d-tjw

+ 1 - 1
fdkanfang-application/src/main/resources/application-test.properties

@@ -85,7 +85,7 @@ sms.common.sign=
 #用户上传全景图通知的管理员的邮箱账号
 admin.email.account=service@4dage.com
 
-oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.point=http://oss-cn-shenzhen-internal.aliyuncs.com
 oss.key=LTAIUrvuHqj8pvry
 oss.secrey=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
 oss.bucket=4d-tjw

+ 1 - 1
fdkanfang-common/src/main/java/com/fdkanfang/common/util/AliyunOssUtil.java

@@ -23,7 +23,7 @@ import java.util.Map;
 public class AliyunOssUtil {
 
 
-    private static final String END_POINT = "http://oss-cn-shenzhen.aliyuncs.com";
+    private static final String END_POINT = "http://oss-cn-shenzhen-internal.aliyuncs.com";
 	private static final String ACCESS_KEY_ID = "LTAIUrvuHqj8pvry";
 	private static final String ACCESS_KEY_SECREY = "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4";
 	private static final String BUCKET_NAME = "4dkankan";

+ 1 - 0
fdkanfang-common/src/main/java/com/fdkanfang/common/util/FileUtils.java

@@ -59,6 +59,7 @@ public class FileUtils {
         in.close();
     }
 
+
     /**
      * 获取类路径
      */

+ 94 - 8
fdkanfang-common/src/main/java/com/fdkanfang/common/util/OssCheckPointUploadUtil.java

@@ -1,15 +1,19 @@
 package com.fdkanfang.common.util;
 
 import com.aliyun.oss.*;
-import com.aliyun.oss.model.CompleteMultipartUploadResult;
-import com.aliyun.oss.model.UploadFileRequest;
-import com.aliyun.oss.model.UploadFileResult;
+import com.aliyun.oss.model.*;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
-import java.io.File;
+import java.io.*;
 
+import com.aliyun.oss.ClientException;
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.OSSException;
+import com.aliyun.oss.model.GetObjectRequest;
+import com.aliyun.oss.model.OSSObject;
 /**
  * @author abnerhou
  * @date 2020/5/28 10:37
@@ -20,16 +24,16 @@ import java.io.File;
 public class OssCheckPointUploadUtil {
 
     @Value("${oss.point}")
-    private String endpoint;
+    private  String endpoint;
 
     @Value("${oss.key}")
-    private String accessKeyId;
+    private  String accessKeyId;
 
     @Value("${oss.secrey}")
-    private String accessKeySecret;
+    private  String accessKeySecret;
 
     @Value("${oss.bucket}")
-    private String bucketName;
+    private  String bucketName;
     public void doUploadThenDelete(String uploadFile , String objectName){
         // 创建OSSClient实例。
         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
@@ -92,4 +96,86 @@ public class OssCheckPointUploadUtil {
             log.error(e.toString() + filePath);
         }
     }
+
+    public static String downloadFileFromOss(String localFilePath,String newFileName,
+                                           String bucketName , String objectKey) throws IOException {
+        if(StringUtils.isNoneBlank(localFilePath , bucketName , objectKey)){
+            // 创建OSSClient实例。
+//            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+            OSS ossClient = new OSSClientBuilder().build("http://oss-cn-shenzhen.aliyuncs.com"
+                    , "LTAIUrvuHqj8pvry", "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4");
+
+            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
+            OSSObject ossObject = ossClient.getObject(new GetObjectRequest( bucketName, objectKey));
+            String fileName = "";
+            if(StringUtils.isNotBlank(newFileName)){
+                fileName = newFileName;
+            }else{
+                int index = objectKey.lastIndexOf("/");
+                if(index != -1){
+                    fileName = objectKey.substring(index + 1 , objectKey.length());
+                }
+            }
+
+            File directory = new File(localFilePath);
+            if(!directory.exists()){
+                directory.mkdirs();
+            }
+            localFilePath += fileName;
+            if(null != ossObject){
+                File file = new File(localFilePath);
+                if(file.exists()){
+                    FileUtils.deleteFile(localFilePath);
+                    file = new File(localFilePath);
+                }
+                InputStream inputStream = ossObject.getObjectContent();
+                if(null == inputStream){
+                    log.error("获取oss返回的输入流失败");
+                    return localFilePath;
+                }
+                BufferedInputStream inputBuff = new BufferedInputStream(inputStream);
+                // 输出缓冲流
+                BufferedOutputStream stream = null;
+                try {
+                    stream = new BufferedOutputStream(new FileOutputStream(file));
+                    int len = 0;
+                    byte[] buffer = new byte[1024];
+                    while ((len = inputBuff.read(buffer)) != -1) {
+                        stream.write(buffer, 0, len);
+                    }
+                } catch (FileNotFoundException e) {
+                    e.printStackTrace();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }finally {
+                    if(null != stream){
+                        stream.flush();
+                        stream.close();
+                        inputBuff.close();
+                    }
+                }
+
+            }
+            // 关闭OSSClient。
+            ossClient.shutdown();
+        }else{
+            log.error("入参为空,无法下载oss的照片");
+        }
+        return localFilePath;
+    }
+
+
+   /* public static void main(String[] args){
+
+        try {
+            downloadFileFromOss("E:\\data\\fdkanfang\\t-sk-93IabtI45\\input_img\\" ,"",
+                    "4d-tjw" , "4dkanfang/3.jpg");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        System.out.println("done==");
+    }*/
+
+
 }

+ 153 - 75
fdkanfang-web/src/main/java/com/fdkanfang/web/backend/HouseController.java

@@ -3,7 +3,6 @@ package com.fdkanfang.web.backend;
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.bean.copier.CopyOptions;
 import cn.hutool.core.io.FileUtil;
-import cn.hutool.core.io.resource.ResourceUtil;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.fdkanfang.common.constant.ConstantFilePath;
@@ -35,9 +34,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;
-import org.springframework.util.FileCopyUtils;
 import org.springframework.web.bind.annotation.*;
-import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
 import javax.mail.MessagingException;
@@ -215,76 +212,77 @@ public class HouseController extends BaseController {
             String imageHighPath = null;
             String imageLowPath = null;
             for (String filename : fileNames) {
-
-//                filename = checkAndChangeFileName(filename);
                 JSONObject jsonObject = JSON.parseObject(filename);
                 if(null == jsonObject){
                     log.error("转换json对象失败:{}" , filename);
                     continue;
                 }
+                //原始照片在oss的路径
                 String origin = jsonObject.getString("origin");
                 String newFileName = jsonObject.getString("name");
                 if(!StringUtils.isNoneEmpty(origin , newFileName)){
                     continue;
                 }
-
-                //将文件复制到本地,成新的文件名,将数据库中的原照片,都修改成新的文件名
-                ImageEntity imageEntity = imageService2.findByFileName(origin);
-                if(null == imageEntity){
-                    log.warn("照片[{}]不存在" , origin);
+                checkAndChangeFileName(newFileName);
+                //从oss获取照片,然后用新的名字下载到本地
+                Map<String , Object> ossInfo = getOssBucketInfo(origin);
+                if(CollectionUtils.isEmpty(ossInfo)){
+                    log.info("oss数据解析失败,跳过");
                     continue;
                 }
-                // 获取图片房间类型
-                String imageType = StringUtils.substringBefore(newFileName, "_");
-                imageEntity.setType(imageType);
-                if(StringUtils.isNotBlank(imageEntity.getLocalPath())){
-                    String localPath = imageEntity.getLocalPath();
-                    int index = localPath.indexOf(imageEntity.getFileName());
-                    if(index == -1){
-                        log.warn("照片本地路径格式有误");
-                        continue;
-                    }
-                    String localDirectory = localPath.substring(0 , index);
-                    String newFileFullPath = localDirectory + newFileName;
-                    log.info("将进行文件名称修改,将[{}]修改成:[{}]" , localPath , newFileFullPath);
-                    File oldImage = new File(localPath);
-                    File newImage = new File(newFileFullPath);
-                    try {
-                        FileCopyUtils.copy(oldImage , newImage);
-                    } catch (IOException e) {
-                        log.error("复制本地照片出现异常");
-                        e.printStackTrace();
-                    }
-                    boolean delLocal = FileUtils.deleteFile(localPath);
-                    if(!delLocal){
-                        log.error("删除改名之前的照片[{}]失败" , localPath);
-                    }
-                    imageEntity.setLocalPath(newFileFullPath);
-                    imageEntity.setPath(newFileFullPath);
+                String bucketName = (String) ossInfo.get("ossBucket");
+                String ossObjKey = (String) ossInfo.get("ossKey");
+                if(!StringUtils.isNoneBlank(bucketName , ossObjKey)){
+                    log.info("oss的bucketName数据解析失败,跳过");
+                    continue;
                 }
-                imageEntity.setFileName(newFileName);
-                if(StringUtils.isNotBlank(imageEntity.getVerticalPath())){
-                    String verticalPath = imageEntity.getVerticalPath();
-                    int tmpIndex = verticalPath.indexOf(origin);
-                    if(tmpIndex != -1){
-                        String newVerticalPath = verticalPath.substring(0 ,tmpIndex);
-                        newVerticalPath += newFileName;
-                        imageEntity.setVerticalPath(newVerticalPath);
-                    }
+                String oldImageName = "";
+                int index = ossObjKey.lastIndexOf("/");
+                if(index == -1){
+                    log.error("[{}]获取不到改名前的名称" , ossObjKey);
+                    continue;
                 }
-                int update = imageService2.update(imageEntity);
-                if(update != 1){
-                    log.error("更新照片[{}]的数据失败" , origin);
-                    throw new CommonBaseException(ResultCodeEnum.D101 ,"更新照片数据失败");
+                oldImageName = ossObjKey.substring(index);
+                log.info("照片改名前的名称为:{}" , oldImageName);
+                //这里改名
+                String newFilePath = directoryName + newFileName;
+                String oldFilePath = directoryName + oldImageName;
+                File oldImageFile = new File(oldFilePath);
+                File newImageFile = new File(newFilePath);
+                try {
+                    org.apache.commons.io.FileUtils.copyFile(oldImageFile, newImageFile);
+                } catch (IOException e) {
+                    log.error("改名操作出现异常,跳过");
+                    e.printStackTrace();
+                    continue;
                 }
+                boolean del = FileUtils.deleteFile(oldFilePath);
+                log.info("删除的文件目录为:{},删除结果为:{}" , oldFilePath , del);
+                //用于四维看看的
                 imageHighPath = OUTPATH + sceneCode + "/output_img/" + newFileName;
+                //用于sketch,sketch的image表需要存储这个路径,给前端使用
                 imageLowPath = OUTPATH + sceneCode + "/output_img_low/" + newFileName;
                 // 提前把算法的图片路径存到数据库,但不代表算法运行成功,最后好是要看house的状态;
                 String ossVerticalHighPath = ConstantFilePath.OSS_IMAGE_PATH+ sceneCode+"/pan/high/"+ newFileName;
                 String ossVerticalLowPath = ConstantFilePath.OSS_IMAGE_PATH+ sceneCode+"/pan/low/"+ newFileName;
-                // 封装垂直校验后的图片到信息到oss
-                ossVerticalImageHighMap.put(imageHighPath, ossVerticalHighPath);
-                ossVerticalImageLowMap.put(imageLowPath, ossVerticalLowPath);
+                //TODO:这里需要计算分辨率
+                //照片分辨率
+                int totalResolutinRate = 0;
+                try {
+                    totalResolutinRate = getImageResolutinoRate(newImageFile);
+                } catch (IOException e) {
+                    log.error("计算照片[{}]分辨率出异常" , newFilePath);
+                    e.printStackTrace();
+                }
+                ImageResolutionRate maxResolutionRate = ImageResolutionRate.getResolutionRateByRate(totalResolutinRate);
+                log.info("照片{}的像素为:{}" , newFilePath , totalResolutinRate);
+
+                addNewImage(param.getId() , newFileName , newFilePath , ossVerticalLowPath, maxResolutionRate);
+                // 封装垂直校验后的图片到信息到oss,key为照片在本地的路径,value为照片在oss中的目录路径
+                //给四维看看的前端加载使用
+                ossVerticalImageHighMap.put(imageHighPath, ossVerticalHighPath);   //四维看看用的,文件太大
+                //给sketch的前端使用
+                ossVerticalImageLowMap.put(imageLowPath, ossVerticalLowPath);   //sketch用的,文件适中
                 needSendMqMsg = true;
             }
             insertScene(param.getImageMaxRate() , house);
@@ -317,6 +315,38 @@ public class HouseController extends BaseController {
         return new R(MsgCode.SUCCESS_CODE, house);
     }
 
+    public Map<String ,Object> getOssBucketInfo(String ossUrl){
+        Map<String , Object> result = new HashMap<>();
+        if(StringUtils.isBlank(ossUrl)){
+            return result;
+        }
+        log.info("oss资源的路径为:{}" , ossUrl);
+        int bucketStar = ossUrl.indexOf("://");
+        if(bucketStar == -1){
+            log.error("oss路径没有://");
+            return result;
+        }
+        bucketStar += 3;
+        int buckeEnd = ossUrl.indexOf(".");
+        if(buckeEnd == -1){
+            log.error("oss路径没有./");
+            return result;
+        }
+        String buckeName = ossUrl.substring(bucketStar , buckeEnd);
+        log.info("解析的buckeName={}" , buckeName);
+        int keyStart = ossUrl.indexOf("com/");
+        if(keyStart == -1){
+            log.error("oss路径没有com/");
+            return result;
+        }
+        keyStart += 5;
+        String key = ossUrl.substring(keyStart , ossUrl.length());
+        log.info("解析出来的oss key={}" , key);
+        result.put("ossBucket" , buckeName);
+        result.put("ossKey" , key);
+        return result;
+    }
+
 
 //    @RequiresRoles(value = {"admin", "edit", "upload"}, logical = Logical.OR)
     @ApiOperation("生成houseId和场景码")
@@ -326,7 +356,7 @@ public class HouseController extends BaseController {
        return new R(MsgCode.SUCCESS_CODE, generateHouseIdAndSceneNum());
     }
 
-    @ApiOperation("上传照片")
+    @ApiOperation("从OSS上下载原始照片并生成缩略图")
     @PostMapping(value = "uploadImages")
     @Transactional(rollbackFor = Exception.class)
     @ApiImplicitParams({
@@ -334,24 +364,11 @@ public class HouseController extends BaseController {
             @ApiImplicitParam(name = "sceneCode", value = "场景码", paramType = "query", required = true, dataType = "String"),
             @ApiImplicitParam(name = "houseId", value = "房间ID", paramType = "query", required = true, dataType = "Long")
     })
-    public Result uploadImages(@RequestParam(name = "file") CommonsMultipartFile file ,
-                               @RequestParam(name = "sceneCode") String sceneCode,
-                               @RequestParam(name = "houseId") Long houseId){
-        Map<String, Object> imageResult = new HashMap<>();
-        if(null != file){
-            String filename = file.getOriginalFilename();
-            filename = checkAndChangeFileName(filename);
-            String directoryName = OUTPATH + sceneCode + File.separator + "input_img"+ File.separator;
-//            String ossVerticalHighPath = ConstantFilePath.OSS_IMAGE_PATH+ sceneCode+"/pan/high/"+ filename;
-            String ossVerticalHighPath = ConstantFilePath.OSS_IMAGE_PATH+ sceneCode+"/pan/high/";
-            try {
-              imageResult  = addAndGetResolutionRate(file , filename , directoryName ,
-                      ossVerticalHighPath , houseId);
-            } catch (IOException e) {
-                log.error("保存照片到本地和持久化image对象出现异常:{}" , e);
-            }
-        }
-         return Result.success(imageResult);
+    public Result uploadImages(@RequestParam(name = "sceneCode") String sceneCode,
+                               @RequestParam(name = "ossBucketName") String ossBucketName,
+                               @RequestParam(name = "ossObjectKey") String ossObjectKey){
+
+         return Result.success("成功" , genScaleImage(ossBucketName , ossObjectKey , sceneCode));
     }
 
 
@@ -383,6 +400,45 @@ public class HouseController extends BaseController {
         }
     }
 
+    public String genScaleImage(String ossBucketName , String ossObjectKey  , String sceneCode){
+        String scalImageOssUrl = "";
+        if(!StringUtils.isNoneEmpty(ossBucketName)){
+            log.error("oss的bucketName 和ossKey不能为空");
+            return scalImageOssUrl;
+        }
+        try {
+            String fileName = "";
+            int index = ossObjectKey.lastIndexOf("/");
+            if(index != -1){
+                fileName = ossObjectKey.substring(index + 1 , ossObjectKey.length());
+            }else{
+                log.error("ossObjectKey[{}]的格式不正确,无法提取文件名" , ossObjectKey);
+            }
+            String directoryName = OUTPATH + sceneCode + File.separator + "input_img"+ File.separator;
+            String localFile =  ossCheckPointUploadUtil.downloadFileFromOss(directoryName , "",
+                   ossBucketName , ossObjectKey);
+           if(StringUtils.isNotBlank(localFile)){
+               //生成缩略图,并上传到oss
+               String scalImageFullPath = directoryName + "scal_" + fileName;
+//               Thumbnails.of(localFile).scale(0.3).outputQuality(0.8f).toFile(scalImageFullPath);
+               Thumbnails.of(localFile).size(980,980).toFile(scalImageFullPath);
+               String imageOssPath =  ossPath + "scal_" + fileName;
+               log.info("生成的照片上传oss的路径:{}" , imageOssPath);
+               ossCheckPointUploadUtil.upload2(scalImageFullPath, imageOssPath);
+               scalImageOssUrl = ossQueryUrl + imageOssPath;
+               //删除缩略图的本地文件
+               boolean delScalResult = FileUtils.deleteFile(scalImageFullPath);
+               if(!delScalResult){
+                   log.error("删除本地缩略图[{}]失败" , scalImageFullPath);
+               }
+           }
+        } catch (IOException e) {
+            log.error("从oss上下载照片到本地出现异常");
+            e.printStackTrace();
+        }
+        return scalImageOssUrl;
+    }
+
     @Transactional(rollbackFor = Exception.class)
 //    public ImageResolutionRate addAndGetResolutionRate(MultipartFile file , String filename,String directoryName ,
     public Map<String ,Object> addAndGetResolutionRate(CommonsMultipartFile file , String filename,
@@ -393,9 +449,6 @@ public class HouseController extends BaseController {
             log.error("房源id或者文件为空,无法生成image记录");
             return new HashMap<>();
         }
-        // 获取图片房间类型
-//        String imageType = StringUtils.substringBefore(filename, "_");
-
         File dir = new File(directoryName);
         if(!dir.exists()){
             dir.mkdirs();
@@ -452,6 +505,31 @@ public class HouseController extends BaseController {
         return result;
     }
 
+    private void addNewImage(long houseId,
+                              String imageFileName , String imageLocalPath ,
+                             String ossVerticalHighPath,
+                             ImageResolutionRate maxResolutionRate){
+        ImageEntity image = new ImageEntity();
+        // 获取图片房间类型
+        String imageType = StringUtils.substringBefore(imageFileName, "_");
+        image.setType(imageType);
+        image.setVerticalPath(ossVerticalHighPath);
+        image.setFileName(imageFileName);
+        // 这个参数给前端用,只要有文件名就可以了
+        image.setPath(imageLocalPath);
+        image.setLocalPath(imageLocalPath);
+
+        image.setHouseId(houseId);
+        // 默认所有图片都是一楼
+        image.setFloor(1);
+
+        image.setResolutionRate(null != maxResolutionRate ? maxResolutionRate.name() : "TWO_K");
+        int insert = imageService2.save(image);
+        if(insert != 1){
+            throw  new CommonBaseException(ResultCodeEnum.D101, "新增image记录失败");
+        }
+    }
+
     private String generalRandFileName(String fileName){
         if(StringUtils.isBlank(fileName)){
             return "";