Przeglądaj źródła

修改代码逻辑,添加报表数据获取接口

syh 5 lat temu
rodzic
commit
aa616c10f0

+ 5 - 0
jeecg-boot-module-system/pom.xml

@@ -53,6 +53,11 @@
             <version>2.0.2</version>
             <scope>compile</scope>
         </dependency>
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.5.0</version>
+        </dependency>
     </dependencies>
 
     <build>

Plik diff jest za duży
+ 10 - 3
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/ByteDanceTemplateController.java


+ 29 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/ReportController.java

@@ -0,0 +1,29 @@
+package org.jeecg.modules.ctop.controller;
+
+import com.alibaba.fastjson.JSONObject;
+import org.jeecg.modules.ctop.service.IReportService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.Map;
+
+@RestController
+@RequestMapping("report")
+public class ReportController {
+    @GetMapping("advertiser")
+    public Map<String, Object> advertiserReport(String accountId, String startDate, String endDate, String timeGranularity) {
+        return reportService.getAdvertiserReport(accountId, startDate, endDate, timeGranularity);
+    }
+
+    @GetMapping("campaign")
+    public Map<String, Object> campaignReport(@RequestBody JSONObject conditions) {
+        return reportService.getCampaignReport(conditions);
+    }
+
+    @Autowired
+    private IReportService reportService;
+}

+ 47 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/entity/FileInfo.java

@@ -3,6 +3,7 @@ package org.jeecg.modules.ctop.entity;
 import java.io.Serializable;
 import java.util.Date;
 
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
@@ -41,6 +42,21 @@ public class FileInfo {
     @Excel(name = "文件名称", width = 15)
     @ApiModelProperty(value = "文件名称")
     private String fileName;
+
+    /**
+     * md5
+     */
+    @Excel(name = "md5", width = 15)
+    @ApiModelProperty(value = "文件MD5值")
+    private String md5;
+
+    /**
+     * 平台文件id
+     */
+    @Excel(name = "平台文件id")
+    @ApiModelProperty(value = "平台文件id")
+    private String fileId;
+
     /**
      * 文件类型
      */
@@ -61,6 +77,15 @@ public class FileInfo {
     @Excel(name = "文件地址", width = 15)
     @ApiModelProperty(value = "文件地址")
     private String path;
+
+    @Excel(name = "头条账号id", width = 15)
+    @ApiModelProperty(value = "头条账号id")
+    private Long accountId;
+
+    @Excel(name = "广告主id", width = 15)
+    @ApiModelProperty(value = "广告主id")
+    private String advertiserId;
+
     @Excel(name = "文件访问路径", width = 15)
     @ApiModelProperty(value = "文件访问路径")
     private String fileUrl;
@@ -75,6 +100,28 @@ public class FileInfo {
     @ApiModelProperty(value = "updateTime")
     private Date updateTime;
 
+    public FileInfo(String md5Hex, JSONObject data, String advertiserId, CTopOauthToken token, String imageUrl, String imagePath, String fileType, String platformType) {
+        this.type = fileType;
+        if (type.equals("IMAGE")) {
+            this.fileId = data.getString("id");
+        } else {
+            this.fileId = data.getString("video_id");
+        }
+        this.fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
+        Date now = new Date();
+        this.createTime = now;
+        this.updateTime = now;
+        this.accountId = token.getAccountId();
+        this.advertiserId = token.getAdvertiserId();
+        this.fileUrl = imageUrl;
+        this.path = imagePath;
+        this.platformType = platformType;
+        this.md5 = md5Hex;
+    }
+
+    public FileInfo() {
+    }
+
     @Override
     public String toString() {
         return "FileInfo{" +

+ 3 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/service/IFileInfoService.java

@@ -6,6 +6,7 @@ import org.jeecg.modules.ctop.entity.FileInfo;
 import com.baomidou.mybatisplus.extension.service.IService;
 
 import javax.servlet.http.HttpServletRequest;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -25,4 +26,6 @@ public interface IFileInfoService extends IService<FileInfo> {
     Map<String, Object> getIndustryList(String accountId, Integer level);
 
     JSONArray getByteDanceIndustryList(HttpServletRequest req);
+
+    List<FileInfo> getFileInfoByMd5(String md5);
 }

+ 11 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/service/IReportService.java

@@ -0,0 +1,11 @@
+package org.jeecg.modules.ctop.service;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.util.Map;
+
+public interface IReportService {
+    Map<String, Object> getAdvertiserReport(String accountId, String startDate, String endDate, String timeGranularity);
+
+    Map<String, Object> getCampaignReport(JSONObject conditions);
+}

+ 158 - 30
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/service/impl/FileInfoServiceImpl.java

@@ -38,11 +38,13 @@ import org.jeecg.modules.system.service.ISysCategoryService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.core.io.FileSystemResource;
 import org.springframework.stereotype.Service;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.*;
+import java.net.HttpURLConnection;
 import java.net.URI;
 import java.net.URL;
 import java.util.Date;
@@ -59,13 +61,14 @@ import java.util.Map;
 @Service
 public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {
     private static final Logger logger = LoggerFactory.getLogger(FileInfoServiceImpl.class);
+    private FileInfo fileInfo;
 
     @Override
     public Map<String, Object> uploadVideoToBytedance(String accountId, String videoUrl) {
         Map<String, Object> resultMap = new HashMap<>();
         //TODO查询是否已经上传过头条平台
         CTopOauthToken token = tokenService.getOAuthTokenByAccountId(accountId);
-        JSONObject resultObject = uploadAdvideo(token.getAccessToken(), videoUrl, token.getAccountId() + "");
+        JSONObject resultObject = uploadAdvideo(token, videoUrl, token.getAccountId() + "");
         System.out.println(resultObject);
         Integer code = resultObject.getInteger("code");
         String message = resultObject.getString("message");
@@ -74,11 +77,10 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
             ResultMapUtils.setResultMap(resultMap, StatusCode.BYTEDANCE_VIDEO_UPLOAD_FAIL.getCode());
             return resultMap;
         }
-        JSONObject data = resultObject.getJSONObject("data");
-        ByteDanceVideoInfo videoInfo = new ByteDanceVideoInfo(data, token);
-        videoInfoMapper.insert(videoInfo);
+        fileInfo = (FileInfo) resultObject.get("file");
+
         ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
-        resultMap.put("videoId", videoInfo.getId());
+        resultMap.put("videoId", fileInfo.getFileId());
         return resultMap;
     }
 
@@ -93,7 +95,7 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
         CTopOauthToken token = tokenService.getOAuthTokenByAccountId(accountId);
         JSONArray imageIds = new JSONArray();
         for (int i = 0; i < imageUrls.length; i++) {
-            JSONObject resultObject = uploadAdImage(token.getAccessToken(), imageUrls[i], token.getAccountId() + "");
+            JSONObject resultObject = uploadAdImage(token, imageUrls[i], token.getAccountId() + "");
             System.out.println(resultObject);
             Integer code = resultObject.getInteger("code");
             String message = resultObject.getString("message");
@@ -102,10 +104,8 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
                 ResultMapUtils.setResultMap(resultMap, StatusCode.BYTEDANCE_VIDEO_UPLOAD_FAIL.getCode());
                 return resultMap;
             }
-            JSONObject data = resultObject.getJSONObject("data");
-            ByteDanceVideoInfo videoInfo = new ByteDanceVideoInfo(data, token);
-            videoInfoMapper.insert(videoInfo);
-            imageIds.add(videoInfo.getId());
+            FileInfo fileInfo = (FileInfo) resultObject.get("file");
+            imageIds.add(fileInfo.getFileId());
         }
         ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
         resultMap.put("imageIds", imageIds);
@@ -121,7 +121,7 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
     public Map<String, Object> uploadImageToBytedance(String accountId, String imageUrl) {
         Map<String, Object> resultMap = new HashMap<>();
         CTopOauthToken token = tokenService.getOAuthTokenByAccountId(accountId);
-        JSONObject resultObject = uploadAdImage(token.getAccessToken(), imageUrl, token.getAccountId() + "");
+        JSONObject resultObject = uploadAdImage(token, imageUrl, token.getAccountId() + "");
         Integer code = resultObject.getInteger("code");
         String message = resultObject.getString("message");
         if (null == code || code != 0) {
@@ -129,19 +129,18 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
             ResultMapUtils.setResultMap(resultMap, StatusCode.BYTEDANCE_IMAGE_UPLOAD_FAIL.getCode());
             return resultMap;
         }
-        JSONObject data = resultObject.getJSONObject("data");
-        ByteDanceImageInfo imageInfo = new ByteDanceImageInfo(data, token);
-        imageInfoService.saveOrUpdate(imageInfo);
+        FileInfo fileInfo = (FileInfo) resultObject.get("file");
         ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
         JSONArray array = new JSONArray();
-        array.add(imageInfo.getId());
+        array.add(fileInfo.getFileId());
         resultMap.put("imageIds", array);
         return resultMap;
     }
 
     @Autowired
     private IByteDanceImageInfoService imageInfoService;
-
+    @Autowired
+    FileInfoMapper fileInfoMapper;
     @Override
     public Map<String, Object> getIndustryList(String accountId, Integer level) {
         Map<String, Object> resultMap = new HashMap<>();
@@ -201,6 +200,13 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
         return result;
     }
 
+    @Override
+    public List<FileInfo> getFileInfoByMd5(String md5) {
+        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("md5", md5).orderByDesc("create_time");
+        return fileInfoMapper.selectList(queryWrapper);
+    }
+
 
     @Autowired
     private ISysCategoryService categoryService;
@@ -256,12 +262,55 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
         return null;
     }
 
-    public JSONObject uploadAdImage(String accessToken, String imageUrl, String advertiserId) {
+    public JSONObject uploadAdImage(CTopOauthToken token, String imageUrl, String advertiserId) {
+        JSONObject result = new JSONObject();
+        //1:下载文件到本地
+        String imagePath = downLoadByURL(imageUrl);
+        //2: 获取MD5值
+        String md5Hex = null;
+        try {
+            md5Hex = DigestUtils.md5Hex(new FileInputStream(imagePath));
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        //3: 根据MD5值查询是否已经上传过服务器
+        List<FileInfo> getFileInfo = getFileInfoByMd5(md5Hex);
+        if (null != getFileInfo && getFileInfo.size() > 0) {//表示已经上传过服务器
+            result.put("code", 0);
+            result.put("file", getFileInfo.get(0));
+            result.put("message", "图片上传成功");
+            result.put("success", true);
+            return result;
+        }
+        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("md5", md5Hex);
+        fileInfoMapper.delete(queryWrapper);
+
+        //文件上传
+        JSONObject bytedanceObject = imageUpload(token, advertiserId, imageUrl);
+        if (null == bytedanceObject) {
+            logger.info("今日头条图片上传失败");
+            result.put("code", -1);
+            result.put("message", "今日头条文件上传失败");
+            return result;
+        }
+        JSONObject data = bytedanceObject.getJSONObject("data");
+        FileInfo fileInfo = new FileInfo(md5Hex, data, advertiserId, token, "https:" + imageUrl, imagePath, "IMAGE", "1");
+        fileInfoMapper.insert(fileInfo);
+        result.put("code", 0);
+        result.put("file", fileInfo);
+        result.put("message", "图片上传成功");
+        result.put("success", true);
+        return result;
+    }
+
+    private JSONObject imageUpload(CTopOauthToken token, String advertiserId, String imageUrl) {
+        JSONObject result = null;
         // 请求地址
         String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_file_image_ad");
         // 构造请求
         HttpPost httpPost = new HttpPost(url);
-        httpPost.setHeader("Access-Token", accessToken);
+        httpPost.setHeader("Access-Token", token.getAccessToken());
         MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
         // 其他参数
         entityBuilder.addTextBody("advertiser_id", advertiserId);
@@ -278,13 +327,13 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
             response = client.execute(httpPost);
             if (response != null && response.getStatusLine().getStatusCode() == 200) {
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
-                StringBuffer result = new StringBuffer();
+                StringBuffer buffer = new StringBuffer();
                 String line = "";
                 while ((line = bufferedReader.readLine()) != null) {
-                    result.append(line);
+                    buffer.append(line);
                 }
                 bufferedReader.close();
-                return JSONObject.parseObject(result.toString());
+                return JSONObject.parseObject(buffer.toString());
             }
         } catch (ClientProtocolException e) {
             e.printStackTrace();
@@ -303,25 +352,103 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
         return null;
     }
 
-    public JSONObject uploadAdvideo(String accessToken, String videoUrl, String advertiserId) {
+    @Value("${jeecg.path.image-upload}")
+    private String imageUploadPath;
+    @Value("${jeecg.path.video-upload}")
+    private String videoUploadPath;
+
+    public String downLoadByURL(String fileUrl) {
+        //获取文件名,文件名实际上在URL中可以找到
+        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
+        //这里服务器上要将此图保存的路径
+        String savePath = this.imageUploadPath + fileName;
+        try {
+            URL url = new URL("https:" + fileUrl);/*将网络资源地址传给,即赋值给url*/
+            /*此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流*/
+            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+            DataInputStream in = new DataInputStream(connection.getInputStream());
+            /*此处也可用BufferedInputStream与BufferedOutputStream*/
+            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
+            /*将参数savePath,即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
+            byte[] buffer = new byte[4096];
+            int count = 0;
+            /*将输入流以字节的形式读取并写入buffer中*/
+            while ((count = in.read(buffer)) > 0) {
+                out.write(buffer, 0, count);
+            }
+            out.close();/*后面三行为关闭输入输出流以及网络资源的固定格式*/
+            in.close();
+            connection.disconnect();
+            //返回内容是保存后的完整的URL
+            return savePath;/*网络资源截取并存储本地成功返回true*/
+
+        } catch (Exception e) {
+            System.out.println(e + fileUrl + savePath);
+            return null;
+        }
+    }
+
+    public JSONObject uploadAdvideo(CTopOauthToken token, String videoUrl, String advertiserId) {
+        JSONObject result = new JSONObject();
+        //1:下载文件到本地
+        String videoPath = downLoadByURL(videoUrl);
+        //2: 获取MD5值
+        String md5Hex = null;
+        try {
+            md5Hex = DigestUtils.md5Hex(new FileInputStream(videoPath));
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        //3: 根据MD5值查询是否已经上传过服务器
+        List<FileInfo> getFileInfo = getFileInfoByMd5(md5Hex);
+        if (null != getFileInfo && getFileInfo.size() > 0) {//表示已经上传过服务器
+            result.put("code", 0);
+            result.put("file", getFileInfo.get(0));
+            result.put("message", "视频上传成功");
+            result.put("success", true);
+            return result;
+        }
+
+        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("md5", md5Hex);
+        fileInfoMapper.delete(queryWrapper);
+
+        //文件上传
+        JSONObject bytedanceObject = videoUpload(token, advertiserId, videoPath);
+        if (null == bytedanceObject) {
+            logger.info("今日头条视频上传失败");
+            result.put("code", -1);
+            result.put("message", "今日头条视频上传失败");
+            return result;
+        }
+        JSONObject data = bytedanceObject.getJSONObject("data");
+        FileInfo fileInfo = new FileInfo(md5Hex, data, advertiserId, token, "https:" + videoUrl, videoPath, "VIDEO", "1");
+        fileInfoMapper.insert(fileInfo);
+        result.put("code", 0);
+        result.put("file", fileInfo);
+        result.put("message", "视频上传成功");
+        result.put("success", true);
+        return result;
+
+    }
+
+    private JSONObject videoUpload(CTopOauthToken token, String advertiserId, String videoPath) {
         CloseableHttpResponse response = null;
         CloseableHttpClient client = null;
         // 请求地址
         String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_file_video_ad");
         // 构造请求
         HttpPost httpPost = new HttpPost(url);
-        httpPost.setHeader("Access-Token", accessToken);
+        httpPost.setHeader("Access-Token", token.getAccessToken());
         // 文件参数
         try {
-            videoUrl = "https:" + videoUrl;
-            URI uri = new URI(videoUrl);
-            logger.info("video" + videoUrl);
-            FileBody file = new FileBody(new File(uri));
-            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("video_file", file);
+
+            FileBody file = new FileBody(new File(videoPath));
+            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
+                    .addPart("video_file", file);
             // 其他参数
             entityBuilder.addTextBody("advertiser_id", advertiserId);
-            //TODO 需要后期优化修改代码逻辑
-            entityBuilder.addTextBody("image_signature", DigestUtils.md5Hex(new FileInputStream(new File(uri))));
+            entityBuilder.addTextBody("video_signature", DigestUtils.md5Hex(new FileInputStream(new File(videoPath))));
             HttpEntity entity = entityBuilder.build();
             client = HttpClientBuilder.create().build();
             httpPost.setURI(URI.create(url));
@@ -351,6 +478,7 @@ public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> i
         }
         return null;
     }
+
     @Autowired
     private ICTopOauthTokenService tokenService;
 

+ 102 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/service/impl/ReportServiceImpl.java

@@ -0,0 +1,102 @@
+package org.jeecg.modules.ctop.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.jeecg.modules.ctop.entity.CTopOauthToken;
+import org.jeecg.modules.ctop.service.ICTopOauthTokenService;
+import org.jeecg.modules.ctop.service.IReportService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+public class ReportServiceImpl implements IReportService {
+    @Override
+    public Map<String, Object> getAdvertiserReport(String accountId, String startDate, String endDate, String timeGranularity) {
+        CTopOauthToken token = tokenService.getOAuthTokenByAccountId(accountId);
+        JSONObject getObject = getAdvertiserStat(token, startDate, endDate, timeGranularity);
+        return null;
+    }
+
+    @Override
+    public Map<String, Object> getCampaignReport(JSONObject conditions) {
+        return null;
+    }
+
+    @Autowired
+    private ICTopOauthTokenService tokenService;
+
+    public JSONObject getAdvertiserStat(CTopOauthToken token, String startDate, String endDate, String timeGranularity) {
+        String accessToken = token.getAccessToken();
+        final Long advertiserId = token.getAccountId();
+
+        // 请求地址
+        String url = "https://ad.toutiao.com/open_api/2/report/advertiser/get/";
+
+        // 请求参数
+        Map data = new HashMap() {
+            {
+                put("advertiser_id", advertiserId);
+                put("start_date", startDate);
+                put("end_date", endDate);
+                put("time_granularity", timeGranularity);
+            }
+        };
+
+        // 构造请求
+        HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
+            @Override
+            public String getMethod() {
+                return "GET";
+            }
+        };
+
+        httpEntity.setHeader("Access-Token", token.getAccessToken());
+
+        CloseableHttpResponse response = null;
+        CloseableHttpClient client = null;
+
+        try {
+            client = HttpClientBuilder.create().build();
+            httpEntity.setURI(URI.create(url));
+            httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON));
+
+            response = client.execute(httpEntity);
+            if (response != null && response.getStatusLine().getStatusCode() == 200) {
+                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
+                StringBuffer result = new StringBuffer();
+                String line = "";
+                while ((line = bufferedReader.readLine()) != null) {
+                    result.append(line);
+                }
+                bufferedReader.close();
+                return JSONObject.parseObject(result.toString());
+            }
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (response != null) {
+                    response.close();
+                }
+                client.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
+}

+ 44 - 15
jeecg-boot-module-system/src/main/java/org/jeecg/modules/fileupload/service/impl/UploadServiceImpl.java

@@ -2,40 +2,69 @@ package org.jeecg.modules.fileupload.service.impl;
 
 import cn.com.ctop.common.utils.FileEntity;
 import cn.com.ctop.common.utils.FileUploadTool;
+import cn.com.ctop.common.utils.OSSUtils;
+import org.apache.commons.codec.digest.DigestUtils;
 import org.jeecg.modules.ctop.entity.FileInfo;
-import org.jeecg.modules.ctop.mapper.FileInfoMapper;
+import org.jeecg.modules.ctop.service.IFileInfoService;
 import org.jeecg.modules.fileupload.service.IUploadService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 @Service
 public class UploadServiceImpl implements IUploadService {
+    @Value("${jeecg.path.video-upload}")
+    private String videoUpLoadPath;
+    @Value("${jeecg.path.image-upload}")
+    private String imageUpLoadPath;
 
     @Autowired
-    private FileInfoMapper fileInfoMapper;
+    private IFileInfoService fileInfoService;
 
     @Override
     public Map<String, Object> imageUpload(MultipartFile multipartFile, HttpServletRequest request, String type) {
         Map<String, Object> resultMap = new HashMap<>();
-        String savaPath = "D:\\upload\\image";
+        //1: 文件上传至服务器
         FileUploadTool fileUploadTool = new FileUploadTool();
         FileEntity entity;
-        entity = fileUploadTool.createFile(multipartFile, request, savaPath);
-        FileInfo fileInfo = new FileInfo();
-        fileInfo.setFileName(entity.getTitleOrig());
-        fileInfo.setPath(entity.getPath());
-        fileInfo.setType("IMAGE");
-        fileInfo.setFileUrl("http://photocdn.sohu.com/20111207/Img328215620.jpg");
-        fileInfo.setPlatformType(type);
-        fileInfoMapper.insert(fileInfo);
-        resultMap.put("message", "文件上传成功");
-        resultMap.put("success", true);
-        resultMap.put("fileInfo", fileInfo);
+        entity = fileUploadTool.createFile(multipartFile, request, imageUpLoadPath);
+        //2:获取MD5值
+        String md5Hex = null;
+        try {
+            md5Hex = DigestUtils.md5Hex(new FileInputStream(entity.getPath()));
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        //3: 根据MD5值查询是否已经上传过服务器
+        List<FileInfo> getFileInfo = fileInfoService.getFileInfoByMd5(md5Hex);
+        if (null != getFileInfo && getFileInfo.size() > 0) {//表示已经上传过服务器
+            resultMap.put("message", "文件上传成功");
+            resultMap.put("success", true);
+            resultMap.put("fileInfo", getFileInfo.get(0));
+        } else {
+            //未上传过服务器
+            String url = OSSUtils.uploadObject2OSS(new File(entity.getPath()));
+            FileInfo fileInfo = new FileInfo();
+            fileInfo.setFileName(entity.getTitleOrig() + entity.getType());
+            fileInfo.setPath(entity.getPath());
+            fileInfo.setType("IMAGE");
+            fileInfo.setFileUrl(url);
+            fileInfo.setMd5(md5Hex);
+            fileInfo.setPlatformType(type);
+            fileInfoService.save(fileInfo);
+            resultMap.put("message", "文件上传成功");
+            resultMap.put("success", true);
+            resultMap.put("fileInfo", fileInfo);
+        }
         return resultMap;
     }
 
@@ -52,7 +81,7 @@ public class UploadServiceImpl implements IUploadService {
         fileInfo.setType("VIDEO");
         fileInfo.setFileUrl("http://photocdn.sohu.com/20111207/Img328215620.jpg");
         fileInfo.setPlatformType(type);
-        fileInfoMapper.insert(fileInfo);
+        fileInfoService.save(fileInfo);
         resultMap.put("message", "文件上传成功");
         resultMap.put("success", true);
         resultMap.put("fileInfo", fileInfo);

+ 6 - 0
module-common/pom.xml

@@ -33,6 +33,12 @@
             <groupId>com.google.code.gson</groupId>
             <artifactId>gson</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.5.0</version>
+            <scope>compile</scope>
+        </dependency>
     </dependencies>
 
     <build>

+ 15 - 14
module-common/src/main/java/cn/com/ctop/common/utils/OSSUtils.java

@@ -1,6 +1,8 @@
 package cn.com.ctop.common.utils;
 
+import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.OSSClientBuilder;
 import com.aliyun.oss.model.Bucket;
 import com.aliyun.oss.model.OSSObject;
 import com.aliyun.oss.model.ObjectMetadata;
@@ -47,20 +49,20 @@ public class OSSUtils {
      *
      * @return ossClient
      */
-    public static OSSClient getOSSClient() {
-        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
+    public static OSS getOSSClient() {
+        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
     }
 
     /**
      * 创建存储空间
      *
-     * @param ossClient  OSS连接
      * @param bucketName 存储空间
      * @return
      */
-    public static String createBucketName(OSSClient ossClient, String bucketName) {
+    public static String createBucketName(String bucketName) {
         // 存储空间
         final String bucketNames = bucketName;
+        OSS ossClient = OSSUtils.getOSSClient();
         if (!ossClient.doesBucketExist(bucketName)) {
             // 创建存储空间
             Bucket bucket = ossClient.createBucket(bucketName);
@@ -73,10 +75,10 @@ public class OSSUtils {
     /**
      * 删除存储空间buckName
      *
-     * @param ossClient  oss对象
      * @param bucketName 存储空间
      */
-    public static void deleteBucket(OSSClient ossClient, String bucketName) {
+    public static void deleteBucket(String bucketName) {
+        OSS ossClient = OSSUtils.getOSSClient();
         ossClient.deleteBucket(bucketName);
         logger.info("删除" + bucketName + "Bucket成功");
     }
@@ -84,14 +86,14 @@ public class OSSUtils {
     /**
      * 创建模拟文件夹
      *
-     * @param ossClient  oss连接
      * @param bucketName 存储空间
      * @param folder     模拟文件夹名如"qj_nanjing/"
      * @return 文件夹名
      */
-    public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
+    public static String createFolder(String bucketName, String folder) {
         // 文件夹名
         final String keySuffixWithSlash = folder;
+        OSS ossClient = OSSUtils.getOSSClient();
         // 判断文件夹是否存在,不存在则创建
         if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
             // 创建文件夹
@@ -108,12 +110,12 @@ public class OSSUtils {
     /**
      * 根据key删除OSS服务器上的文件
      *
-     * @param ossClient  oss连接
      * @param bucketName 存储空间
      * @param folder     模拟文件夹名 如"qj_nanjing/"
      * @param key        Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
      */
-    public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key) {
+    public static void deleteFile(String bucketName, String folder, String key) {
+        OSS ossClient = OSSUtils.getOSSClient();
         ossClient.deleteObject(bucketName, folder + key);
         logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");
     }
@@ -121,15 +123,13 @@ public class OSSUtils {
     /**
      * 上传图片至OSS
      *
-     * @param ossClient  oss连接
      * @param file       上传文件(文件全路径如:D:\\image\\cake.jpg)
-     * @param bucketName 存储空间
-     * @param folder     模拟文件夹名 如"qj_nanjing/"
      * @return String 返回的唯一MD5数字签名
      */
-    public static String uploadObject2OSS(OSSClient ossClient, File file, String bucketName, String folder) {
+    public static String uploadObject2OSS(File file) {
         String resultStr = null;
         try {
+            OSS ossClient = OSSUtils.getOSSClient();
             // 以输入流的形式上传文件
             InputStream is = new FileInputStream(file);
             // 文件名
@@ -153,6 +153,7 @@ public class OSSUtils {
             metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
             // 上传文件 (上传文件流的形式)
             PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, is, metadata);
+            System.out.println(putResult.toString());
             // 解析结果
             resultStr = putResult.getETag();
         } catch (Exception e) {