浏览代码

修改照片的接口

houweiyu 4 年之前
父节点
当前提交
da3db02def

+ 12 - 0
fdkanfang-application/src/main/java/com/fdkanfang/FdkanfangApplication.java

@@ -4,6 +4,8 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
 /**
  * Created by owen on 2020/2/28 0028 17:18
@@ -12,6 +14,16 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
 @SpringBootApplication
 public class FdkanfangApplication extends SpringBootServletInitializer {
 
+    //设置上传文件的大小,限制为1g
+    @Bean(name = "multipartResolver")
+    public CommonsMultipartResolver getCommonsMultipartResolver() {
+        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
+        multipartResolver.setMaxUploadSize(1024000000);
+        multipartResolver.setMaxInMemorySize(1024000000);
+        return multipartResolver;
+    }
+
+
     public static void main(String[] args) {
         SpringApplication.run(FdkanfangApplication.class, args);
 

+ 13 - 4
fdkanfang-application/src/main/resources/application-dev.properties

@@ -4,7 +4,7 @@
 # \u6570\u636E\u6E90\u914D\u7F6E
 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
-spring.datasource.druid.url=jdbc:mysql://39.108.220.65:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
+spring.datasource.druid.url=jdbc:mysql://120.25.146.52:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
 spring.datasource.druid.username=root
 #spring.datasource.druid.password=4dkk2019%
 spring.datasource.druid.password=4dkk2020test%
@@ -12,7 +12,7 @@ spring.datasource.druid.password=4dkk2020test%
 #testDB
 #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
 #spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
-#spring.datasource.druid.url=jdbc:mysql://39.108.220.65:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
+#spring.datasource.druid.url=jdbc:mysql://120.25.146.52:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
 #spring.datasource.druid.username=root
 #spring.datasource.druid.password=4dkk2019%
 
@@ -43,7 +43,7 @@ spring.datasource.druid.stat-view-servlet.enabled=true
 # Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09
 spring.redis.database=0
 #spring.redis.host=127.0.0.1
-spring.redis.host=39.108.220.65
+spring.redis.host=120.25.146.52
 spring.redis.port=6379
 spring.redis.password=
 # \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4 \u5355\u4F4D ms\uFF08\u6BEB\u79D2\uFF09
@@ -72,7 +72,7 @@ logging.config=classpath:logback-spring.xml
 logging.level.com.fdkanfang=debug
 
 #rabbit MQ
-spring.rabbitmq.host=39.108.220.65
+spring.rabbitmq.host=120.25.146.52
 #spring.rabbitmq.host=localhost
 spring.rabbitmq.port=5672
 spring.rabbitmq.username=guest
@@ -94,3 +94,12 @@ sms.common.sign=
 
 #用户上传全景图通知的管理员的邮箱账号
 admin.email.account=service@4dage.com
+
+
+oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.key=LTAIUrvuHqj8pvry
+oss.secrey=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
+oss.bucket=4d-tjw
+oss.video.file.path=domain/shop/video/
+oss.image.file.path=domain/shop/image/
+oss.query.url=https://houseoss.4dkankan.com/

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

@@ -83,4 +83,13 @@ scene.finish.sms.template.id=SMS_201717882
 sms.common.sign=四维看看Sketch
 
 #用户上传全景图通知的管理员的邮箱账号
-admin.email.account=service@4dage.com
+admin.email.account=service@4dage.com
+
+
+oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.key=LTAIUrvuHqj8pvry
+oss.secrey=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
+oss.bucket=4d-tjw
+oss.video.file.path=domain/shop/video/
+oss.image.file.path=domain/shop/image/
+oss.query.url=https://houseoss.4dkankan.com/

+ 10 - 2
fdkanfang-application/src/main/resources/application-test.properties

@@ -3,7 +3,7 @@
 # \u6570\u636E\u6E90\u914D\u7F6E
 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
-spring.datasource.druid.url=jdbc:mysql://39.108.220.65:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
+spring.datasource.druid.url=jdbc:mysql://120.25.146.52:3306/fdkanfang?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
 spring.datasource.druid.username=root
 #spring.datasource.druid.password=4dkk2019%
 spring.datasource.druid.password=4dkk2020test%
@@ -83,4 +83,12 @@ scene.finish.sms.template.id=SMS_201717882
 sms.common.sign=四维看看Sketch
 
 #用户上传全景图通知的管理员的邮箱账号
-admin.email.account=service@4dage.com
+admin.email.account=service@4dage.com
+
+oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.key=LTAIUrvuHqj8pvry
+oss.secrey=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
+oss.bucket=4d-tjw
+oss.video.file.path=domain/shop/video/
+oss.image.file.path=domain/shop/image/
+oss.query.url=https://houseoss.4dkankan.com/

+ 13 - 0
fdkanfang-common/pom.xml

@@ -173,6 +173,19 @@
             <version>1.6.2</version>
         </dependency>
 
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.3.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>net.coobird</groupId>
+            <artifactId>thumbnailator</artifactId>
+            <version>0.4.12</version>
+        </dependency>
+
+
 
         <!--<dependency>-->
             <!--<groupId>com.fdkankan.scene</groupId>-->

+ 95 - 0
fdkanfang-common/src/main/java/com/fdkanfang/common/util/OssCheckPointUploadUtil.java

@@ -0,0 +1,95 @@
+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 lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+
+/**
+ * @author abnerhou
+ * @date 2020/5/28 10:37
+ * @desciption
+ */
+@Service
+@Slf4j
+public class OssCheckPointUploadUtil {
+
+    @Value("${oss.point}")
+    private String endpoint;
+
+    @Value("${oss.key}")
+    private String accessKeyId;
+
+    @Value("${oss.secrey}")
+    private String accessKeySecret;
+
+    @Value("${oss.bucket}")
+    private String bucketName;
+    public void doUploadThenDelete(String uploadFile , String objectName){
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+        try {
+            File localFile = new File(uploadFile);
+            log.info("Object name = {}" ,objectName);
+            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, objectName);
+            // The local file to upload---it must exist.
+            // 指定上传的本地文件。
+            uploadFileRequest.setUploadFile(uploadFile);
+            log.info("本地文件为:{}" ,uploadFile);
+            // Sets the concurrent upload task number to 5.
+            uploadFileRequest.setTaskNum(5);
+            // Sets the part size to 1MB.
+            uploadFileRequest.setPartSize(1024 * 1024 * 1);
+            // 开启断点续传,默认关闭。
+            // Enables the checkpoint file. By default it's off.
+            uploadFileRequest.setEnableCheckpoint(true);
+            // 记录本地分片上传结果的文件。开启断点续传功能时需要设置此参数,上传过程中的进度信息会保存在该文件中,如果某一分片上传失败,再次上传时会根据文件中记录的点继续上传。上传完成后,该文件会被删除。默认与待上传的本地文件同目录,为uploadFile.ucp。
+            String localCheckFile = localFile.getName() + "_uploadFile.ucp";
+            uploadFileRequest.setCheckpointFile(localCheckFile);
+
+            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
+
+            CompleteMultipartUploadResult multipartUploadResult =
+                    uploadResult.getMultipartUploadResult();
+            log.info("断点续传结果:{}", multipartUploadResult.getETag());
+
+        } catch (OSSException oe) {
+            System.out.println("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            System.out.println("Error Message: " + oe.getErrorMessage());
+            System.out.println("Error Code:       " + oe.getErrorCode());
+            System.out.println("Request ID:      " + oe.getRequestId());
+            System.out.println("Host ID:           " + oe.getHostId());
+        } catch (ClientException ce) {
+            System.out.println("Caught an ClientException, which means the client encountered "
+                    + "a serious internal problem while trying to communicate with OSS, "
+                    + "such as not being able to access the network.");
+            System.out.println("Error Message: " + ce.getMessage());
+        } catch (Throwable e) {
+            e.printStackTrace();
+        } finally {
+            ossClient.shutdown();
+            FileUtils.deleteFile(uploadFile);
+            log.info("关闭oss client,并且本地删除文件");
+        }
+    }
+
+    public void upload2(String filePath, String key1) {
+        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
+        try {
+            File file = new File(filePath);
+            if (!file.exists()) {
+                log.error("要上传的文件不存在:" + filePath);
+            }
+            ossClient.putObject(bucketName, key1, file);
+        } catch (Exception e) {
+            log.error(e.toString() + filePath);
+        }
+    }
+}

+ 3 - 0
fdkanfang-domain/src/main/java/com/fdkanfang/domain/dto/HouseDto.java

@@ -47,6 +47,9 @@ public class HouseDto {
     @ApiModelProperty(value = "制作要求", required = false )
     private String requirement;
 
+    @ApiModelProperty(value = "图片最大像素", required = false )
+    private String imageMaxRate;
+
     // 以下好像没有用到
 
     // 操作者

+ 97 - 26
fdkanfang-web/src/main/java/com/fdkanfang/web/backend/HouseController.java

@@ -3,6 +3,7 @@ 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;
@@ -24,6 +25,7 @@ import com.fdkanfang.web.mq.config.RabbitConfig;
 import com.github.pagehelper.PageInfo;
 import io.swagger.annotations.*;
 import lombok.extern.log4j.Log4j2;
+import net.coobird.thumbnailator.Thumbnails;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.shiro.authz.annotation.Logical;
 import org.apache.shiro.authz.annotation.RequiresRoles;
@@ -35,17 +37,14 @@ import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
 import javax.mail.MessagingException;
 import javax.validation.Valid;
 import java.io.File;
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import java.util.*;
 
 
 /**
@@ -71,6 +70,12 @@ public class HouseController extends BaseController {
     @Value("${admin.email.account}")
     private String adminEmailAccount;
 
+    @Value("${oss.image.file.path}")
+    private String ossPath;
+
+    @Value("${oss.query.url}")
+    private String ossQueryUrl;
+
     @Autowired
     private HouseService2 houseService2;
 
@@ -95,6 +100,9 @@ public class HouseController extends BaseController {
     @Autowired
     private UserService2 userService2;
 
+    @Autowired
+    private OssCheckPointUploadUtil ossCheckPointUploadUtil;
+
 
 
 
@@ -219,16 +227,9 @@ public class HouseController extends BaseController {
                 // 封装垂直校验后的图片到信息到oss
                 ossVerticalImageHighMap.put(imageHighPath, ossVerticalHighPath);
                 ossVerticalImageLowMap.put(imageLowPath, ossVerticalLowPath);
-                try {
-                    ImageResolutionRate tmpResolutionRate = addAndGetResolutionRate(file , directoryName , ossVerticalHighPath , house.getId());
-                    maxResolutionRate = tmpResolutionRate;
-                    needSendMqMsg = true;
-                } catch (IOException e) {
-                    needSendMqMsg = false;
-                    log.error("保存照片到本地和持久化image对象出现异常:{}" , e);
-                }
+                needSendMqMsg = true;
             }
-            insertScene(maxResolutionRate , house);
+            insertScene(param.getImageMaxRate() , house);
             if (needSendMqMsg) {
                 HashMap<Object, Object> mqMap = new HashMap<>();
                 mqMap.put("ossImageHigh", ossVerticalImageHighMap);
@@ -257,11 +258,40 @@ public class HouseController extends BaseController {
         }
         return new R(MsgCode.SUCCESS_CODE, house);
     }
+
+    @ApiOperation("上传照片")
+    @PostMapping(value = "uploadImages")
     @Transactional(rollbackFor = Exception.class)
-    public void insertScene(ImageResolutionRate maxResolutionRate , HouseEntity house){
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "file", value = "文件", paramType = "query", required = true, dataType = "List"),
+            @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;
+            try {
+              imageResult  = addAndGetResolutionRate(file , filename , directoryName ,
+                      ossVerticalHighPath , houseId);
+            } catch (IOException e) {
+                log.error("保存照片到本地和持久化image对象出现异常:{}" , e);
+            }
+        }
+         return Result.success(imageResult);
+    }
+
+
+    @Transactional(rollbackFor = Exception.class)
+    public void insertScene(String  maxResolutionRate , HouseEntity house){
         SceneProEntity sceneProEntity = new SceneProEntity();
         SceneProEditEntity sceneProEditEntity = new SceneProEditEntity();
-        if(ImageResolutionRate.TWO_K.equals(maxResolutionRate)){
+        if(ImageResolutionRate.TWO_K.name().equals(maxResolutionRate)){
             //2k
             sceneProEntity.setSceneScheme(11);
         }else{
@@ -286,18 +316,22 @@ public class HouseController extends BaseController {
     }
 
     @Transactional(rollbackFor = Exception.class)
-    public ImageResolutionRate addAndGetResolutionRate(MultipartFile file , String directoryName ,
-                                                        String ossVerticalHighPath , Long houseId) throws IOException {
+//    public ImageResolutionRate addAndGetResolutionRate(MultipartFile file , String filename,String directoryName ,
+    public Map<String ,Object> addAndGetResolutionRate(CommonsMultipartFile file , String filename,
+                                                       String directoryName ,
+                                                        String ossVerticalHighPath ,
+                                                       Long houseId) throws IOException {
         if(null == file || null == houseId){
             log.error("房源id或者文件为空,无法生成image记录");
-            return null;
+            return new HashMap<>();
         }
-        String filename = file.getOriginalFilename();
-        filename = checkAndChangeFileName(filename);
-
         // 获取图片房间类型
         String imageType = StringUtils.substringBefore(filename, "_");
 
+        File dir = new File(directoryName);
+        if(!dir.exists()){
+            dir.mkdirs();
+        }
         // 本地图片保存位置: /root/data/kanfang/场景码/input_img/xxxx.jpg
         String fileFullPath = directoryName + filename;
         ImageEntity image = new ImageEntity();
@@ -312,16 +346,53 @@ public class HouseController extends BaseController {
         image.setFloor(1);
         image.setType(imageType);
         //将图片保存到本地指定目录filePath eg: /root/data/kanfang/d_9iRDUgn3l/input_img/xxx.jpg
-        int  resolutionRate = FileUtils.downloanAndGetResolutionRate(file.getInputStream(), fileFullPath , true);
+        saveFileToLocal(file , fileFullPath);
+        File localFile = new File(fileFullPath);
+        //生成缩略图,并上传到oss
+        String scalImageFullPath = directoryName + "scal_" + filename;
+        Thumbnails.of(localFile).size(128 , 256).outputQuality(0.8f).toFile(scalImageFullPath);
+        String imageOssPath =  ossPath + file.getOriginalFilename();
+        log.info("生成的照片上传oss的路径:{}" , imageOssPath);
+        ossCheckPointUploadUtil.upload2(scalImageFullPath, imageOssPath);
+        String imageTotalOssUrl = ossQueryUrl + imageOssPath;
         //照片分辨率
-        ImageResolutionRate maxResolutionRate = ImageResolutionRate.getResolutionRateByRate(resolutionRate);
-        log.info("照片{}的像素为:{}" , fileFullPath , resolutionRate);
+        int totalResolutinRate = getImageResolutinoRate(localFile);
+        ImageResolutionRate maxResolutionRate = ImageResolutionRate.getResolutionRateByRate(totalResolutinRate);
+        log.info("照片{}的像素为:{}" , fileFullPath , totalResolutinRate);
         image.setResolutionRate(null != maxResolutionRate ? maxResolutionRate.name() : "TWO_K");
         int insert = imageService2.save(image);
         if(insert != 1){
             throw  new CommonBaseException(ResultCodeEnum.D101, "新增image记录失败");
         }
-        return maxResolutionRate;
+        Map<String , Object> result = new HashMap<>();
+        result.put("rate" , maxResolutionRate.name());
+        result.put("ossUrl" , imageTotalOssUrl);
+        return result;
+    }
+
+    private int getImageResolutinoRate(File localFile) throws IOException {
+        if(null != localFile){
+            int totalResolutinRate = -1;
+            SimpleImageInfo simpleImageInfo = new SimpleImageInfo(localFile);
+            if(null != simpleImageInfo){
+                if(simpleImageInfo.getWidth() <  simpleImageInfo.getHeight()){
+                    totalResolutinRate = simpleImageInfo.getHeight();
+                }else{
+                    totalResolutinRate = simpleImageInfo.getWidth();
+                }
+            }
+            return totalResolutinRate;
+        }
+        return 0;
+    }
+
+    private void saveFileToLocal(CommonsMultipartFile file , String localFullPath) throws IOException {
+
+        if(StringUtils.isBlank(localFullPath) || null == file){
+            return;
+        }
+        File newFile = new File(localFullPath);
+        file.transferTo(newFile);
     }
 
     private String checkAndChangeFileName(String filename){

+ 1 - 0
fdkanfang-web/src/main/java/com/fdkanfang/web/shiro/ShiroConfig.java

@@ -76,6 +76,7 @@ public class ShiroConfig {
         filterRuleMap.put("/admin/login", "anon");
         filterRuleMap.put("/user/login", "anon");
         filterRuleMap.put("/test/**", "anon");
+        filterRuleMap.put("/manage/house/**", "anon");
 
 
         // swagger 不拦截

+ 4 - 1
pom.xml

@@ -44,7 +44,8 @@
         <jwt.version>3.2.0</jwt.version>
         <aliyun.core.version>4.0.3</aliyun.core.version>
         <aliyun.dysmsapi.version>1.1.0</aliyun.dysmsapi.version>
-        <aliyun.oss.version>2.5.0</aliyun.oss.version>
+<!--        <aliyun.oss.version>2.5.0</aliyun.oss.version>-->
+        <aliyun.oss.version>3.8.0</aliyun.oss.version>
         <qiniu.version>7.2.0</qiniu.version>
         <!--<tk.mybatis.version>2.0.3</tk.mybatis.version>-->
         <tk.mybatis.version>2.0.2</tk.mybatis.version>
@@ -90,6 +91,8 @@
             </dependency>
 
 
+
+
             <!-- springboot -->
             <dependency>
                 <groupId>org.springframework.boot</groupId>