Skip to content

Commit

Permalink
Merge pull request #82 from yanyanho/main
Browse files Browse the repository at this point in the history
add cos file storage
  • Loading branch information
hotaplayer authored Dec 11, 2023
2 parents 8e50211 + 301e7d8 commit 21fca6e
Show file tree
Hide file tree
Showing 13 changed files with 305 additions and 73 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
.gitignore
./src/main/resources/

src/main/resources/application-dev.yml

HappyRedPacket.java

# Package Files #
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ https://github.com/spruceid/siwe-go/blob/main/message.go

## build
```
ssh root@43.135.22.107
ssh root@ip
./gradlew build -x test
scp ./dist/apps/dl.jar root@43.135.22.107:/root/Official-website-backend/dist/apps
scp ./dist/apps/dl.jar root@ip:/root/Official-website-backend/dist/apps
```

Expand All @@ -38,4 +38,6 @@ https://github.com/spruceid/siwe-go/blob/main/message.go
- upload pic: https://juejin.cn/post/6844903630416379918
- JPA query: https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl
- JPA : https://www.baeldung.com/hibernate-criteria-queries
- session filter: https://blog.csdn.net/dothetrick/article/details/110356640
- session filter: https://blog.csdn.net/dothetrick/article/details/110356640
- cos: https://cloud.tencent.com/developer/article/1559746
- cos download: https://blog.csdn.net/qq_43960768/article/details/126731733
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ dependencies {
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-graphql
//implementation 'org.springframework.boot:spring-boot-starter-graphql:2.7.17'
implementation 'io.springfox:springfox-boot-starter:3.0.0'

implementation 'com.qcloud:cos_api:5.6.155'

//graphql
// implementation(platform("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:latest.release"))
Expand Down
118 changes: 53 additions & 65 deletions src/main/java/com/dl/officialsite/file/FileController.java
Original file line number Diff line number Diff line change
@@ -1,65 +1,53 @@
//package com.dl.officialsite.file;
//
//import cn.hutool.core.io.IoUtil;
//import com.dl.officialsite.common.base.BaseResponse;
//import com.dl.officialsite.common.enums.CodeEnums;
//import com.dl.officialsite.common.exception.BizException;
//import com.dl.officialsite.ipfs.IPFSService;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.InputStream;
//
///**
// * @ClassName FileController
// * @Author jackchen
// * @Date 2023/10/16 17:07
// * @Description 文件上传
// **/
//@RestController
//@RequestMapping("/file")
//@Data
//@Slf4j
//public class FileController {
//
// private final IPFSService ipfsService;
//
// /**
// * 文件上传
// */
// @PostMapping("/upload")
// public BaseResponse upload(@RequestParam("file") MultipartFile file,
// @RequestParam String address) {
// try {
// String hash = ipfsService.upload(file.getBytes());
// return BaseResponse.successWithData(hash);
// } catch (IOException e) {
// log.error("文件上传失败{}", file.getName());
// throw new BizException(CodeEnums.FAIL_UPLOAD_FAIL.getCode(),
// CodeEnums.FAIL_UPLOAD_FAIL.getMsg());
// }
// }
//
// /**
// * 文件下载
// */
// @GetMapping("/download")
// public void download(@RequestParam String fileHash,
// @RequestParam String address, HttpServletResponse response)
// throws IOException {
// InputStream inputStream = null;
// try {
// inputStream = ipfsService.downloadStream(fileHash);
// } catch (IOException e) {
// log.error("文件下载失败{}", fileHash);
// throw new BizException(CodeEnums.FAIL_DOWNLOAD_FAIL.getCode(),
// CodeEnums.FAIL_DOWNLOAD_FAIL.getMsg());
// }
// response.setContentType("application/octet-stream");
// IoUtil.copy(inputStream, response.getOutputStream());
// }
//}
package com.dl.officialsite.file;//package com.dl.officialsite.file;

import cn.hutool.core.io.IoUtil;
import com.dl.officialsite.common.base.BaseResponse;
import com.dl.officialsite.file.cos.FileService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
* @ClassName FileController
* @Author jackchen
* @Date 2023/10/16 17:07
* @Description 文件上传
**/
@RestController
@RequestMapping("/file")
@Data
@Slf4j
public class FileController {

private final FileService fileService;

/**
* 文件上传
*/
@PostMapping("/upload")
public BaseResponse upload(@RequestParam(required = false) MultipartFile file,
@RequestParam String address) {
String hash = fileService.upload(file);
return BaseResponse.successWithData(hash);
}

/**
* todo
*/
@GetMapping("/download")
public void download(@RequestParam String fileHash,
@RequestParam String address, HttpServletResponse response)
throws IOException {
InputStream inputStream = null;

inputStream = fileService.download(fileHash);

response.setContentType("application/octet-stream");
IoUtil.copy(inputStream, response.getOutputStream());
}
}
65 changes: 65 additions & 0 deletions src/main/java/com/dl/officialsite/file/FileControllerWithipfs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//package com.dl.officialsite.file;
//
//import cn.hutool.core.io.IoUtil;
//import com.dl.officialsite.common.base.BaseResponse;
//import com.dl.officialsite.common.enums.CodeEnums;
//import com.dl.officialsite.common.exception.BizException;
//import com.dl.officialsite.ipfs.IPFSService;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.InputStream;
//
///**
// * @ClassName FileController
// * @Author jackchen
// * @Date 2023/10/16 17:07
// * @Description 文件上传
// **/
//@RestController
//@RequestMapping("/file")
//@Data
//@Slf4j
//public class FileController {
//
// private final IPFSService ipfsService;
//
// /**
// * 文件上传
// */
// @PostMapping("/upload")
// public BaseResponse upload(@RequestParam("file") MultipartFile file,
// @RequestParam String address) {
// try {
// String hash = ipfsService.upload(file.getBytes());
// return BaseResponse.successWithData(hash);
// } catch (IOException e) {
// log.error("文件上传失败{}", file.getName());
// throw new BizException(CodeEnums.FAIL_UPLOAD_FAIL.getCode(),
// CodeEnums.FAIL_UPLOAD_FAIL.getMsg());
// }
// }
//
// /**
// * 文件下载
// */
// @GetMapping("/download")
// public void download(@RequestParam String fileHash,
// @RequestParam String address, HttpServletResponse response)
// throws IOException {
// InputStream inputStream = null;
// try {
// inputStream = ipfsService.downloadStream(fileHash);
// } catch (IOException e) {
// log.error("文件下载失败{}", fileHash);
// throw new BizException(CodeEnums.FAIL_DOWNLOAD_FAIL.getCode(),
// CodeEnums.FAIL_DOWNLOAD_FAIL.getMsg());
// }
// response.setContentType("application/octet-stream");
// IoUtil.copy(inputStream, response.getOutputStream());
// }
//}
32 changes: 32 additions & 0 deletions src/main/java/com/dl/officialsite/file/cos/COSClientConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.dl.officialsite.file.cos;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(COSProperties.class)
public class COSClientConfig {


@Autowired
private COSProperties cosProperties;

@Bean
public COSClient cosClient(){
COSCredentials cred = new BasicCOSCredentials(cosProperties.getSecretId(),cosProperties.getSecretKey());
Region region = new Region(cosProperties.getRegionName());
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}

}
15 changes: 15 additions & 0 deletions src/main/java/com/dl/officialsite/file/cos/COSProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.dl.officialsite.file.cos;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "qcloud")
public class COSProperties {
private String secretId;
private String secretKey;
private String bucketName;
private String regionName;


}
102 changes: 102 additions & 0 deletions src/main/java/com/dl/officialsite/file/cos/FileService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package com.dl.officialsite.file.cos;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileService {

@Autowired
private COSClient cosClient;
@Autowired
private COSProperties cosProperties;

// 支持的文件类型
private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");


public String upload(MultipartFile file) {

// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
File localFile = null;

String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID()+eName;
String key = null;
try {
localFile = File.createTempFile("temp",null);
file.transferTo(localFile);
key = UUID.randomUUID().toString().replace("-","");
PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, localFile);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
} catch (IOException e) {
}
//拼接返回路径
cosClient.shutdown();
String imagePath = "https://" + cosProperties.getBucketName() + ".cos." + cosProperties.getRegionName() + ".myqcloud.com/" + key;
return imagePath;
}

public String uploadImage(MultipartFile file) {
String key = null;
try {
// 1、图片信息校验
// 1)校验文件类型
String type = file.getContentType(); //获取文件格式
if (!suffixes.contains(type)) {
// logger.info("上传失败,文件类型不匹配:{}", type);
return null;
}
// 2)校验图片内容
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null) {
// logger.info("上传失败,文件内容不符合要求");
return null;
}

ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(type);
UUID uuid = UUID.randomUUID();
// 指定要上传到 COS 上对象键 此key是文件唯一标识
key = uuid.toString().replace("-","")+".jpg";
PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, file.getInputStream(),objectMetadata);

//使用cosClient调用第三方接口
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
log.info(putObjectRequest+"");
//返回路径

}catch (Exception e){
e.printStackTrace();
}
cosClient.shutdown();
//拼接返回路径
String imagePath = "https://" + cosProperties.getBucketName() + ".cos." + cosProperties.getRegionName() + ".myqcloud.com/" + key;
return imagePath;
}


//todo
public InputStream download(String fileHash) {
return null;
}
}
1 change: 1 addition & 0 deletions src/main/java/com/dl/officialsite/hiring/Hiring.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class Hiring {

private String invoice;


private String yearlySalary;

private String benefits;
Expand Down
Loading

0 comments on commit 21fca6e

Please sign in to comment.