提交 ed80e0db 作者: 张小凤

oss(upload)

上级 a7c667a7
......@@ -96,13 +96,27 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.taobao.arthas</groupId>
<artifactId>arthas-spring-boot-starter</artifactId>
<version>3.6.3</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
......
package com.mmc.pms.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.mmc.pms.common.ResultBody;
import com.mmc.pms.json.JsonUtil;
import com.mmc.pms.redis.RedisConstant;
import com.mmc.pms.util.OssConstant;
import com.mmc.pms.util.PartUploadInfo;
import com.mmc.pms.util.TDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
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.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Author small @Date 2023/5/23 13:46 @Version 1.0
*/
@Api(tags = {"分片上传"})
@RestController
@RequestMapping("/partupload")
public class PartUploadController {
@Autowired private StringRedisTemplate stringRedisTemplate;
@ApiOperation(value = "初始化分片上传")
@GetMapping("/initPartUpload")
public ResultBody initPartUpload(@RequestParam String fileName, HttpServletRequest httpRequest) {
// 创建OSSClient实例。
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
StringBuffer objectName = new StringBuffer();
objectName.append(OssConstant.BUCKET);
objectName.append("/");
objectName.append(fileName);
objectName.append("-");
objectName.append(TDateUtil.getCurrentDateByType("yyyyMMddHHmm"));
// 创建InitiateMultipartUploadRequest对象。
InitiateMultipartUploadRequest request =
new InitiateMultipartUploadRequest(OssConstant.BUCKET, objectName.toString());
// 如果需要在初始化分片时设置文件存储类型,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
// StorageClass.Standard.toString());
// request.setObjectMetadata(metadata);
// 初始化分片。
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
// 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。
String uploadId = upresult.getUploadId();
// 记录缓存信息
PartUploadInfo pinfo = new PartUploadInfo();
pinfo.setBucketName(OssConstant.BUCKET);
pinfo.setObjectName(objectName.toString());
pinfo.setUploadId(uploadId);
stringRedisTemplate
.opsForValue()
.set(RedisConstant.createPartUploadKey(uploadId), JsonUtil.parseObjToJson(pinfo));
return ResultBody.success(uploadId);
}
@ApiOperation(value = "进行片段上传")
@PostMapping("/partUpload")
public ResultBody partUpload(
@RequestParam("partFile") MultipartFile partFile, @RequestParam("uploadId") String uploadId)
throws IOException {
PartUploadInfo pinfo =
JsonUtil.parseJsonToObj(
stringRedisTemplate.opsForValue().get(RedisConstant.createPartUploadKey(uploadId)),
PartUploadInfo.class);
// 创建OSSClient实例。
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
// partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。
List<PartETag> partETags = new ArrayList<PartETag>();
// 每个分片的大小,用于计算文件有多少个分片。单位为字节。
final long partSize = 1 * 1024 * 1024L; // 1 MB。
// 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
final File sampleFile = new File("D:\\localpath\\examplefile.txt");
long fileLength = sampleFile.length();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// 遍历分片上传。
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
InputStream instream = new FileInputStream(sampleFile);
// 跳过已经上传的分片。
instream.skip(startPos);
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(pinfo.getBucketName());
uploadPartRequest.setKey(pinfo.getObjectName());
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(instream);
// 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。
uploadPartRequest.setPartSize(curPartSize);
// 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。
uploadPartRequest.setPartNumber(i + 1);
// 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。
partETags.add(uploadPartResult.getPartETag());
}
// 创建CompleteMultipartUploadRequest对象。
// 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(
pinfo.getBucketName(), pinfo.getObjectName(), uploadId, partETags);
// 如果需要在完成文件上传的同时设置文件访问权限,请参考以下示例代码。
// completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead);
// 完成上传。
CompleteMultipartUploadResult completeMultipartUploadResult =
ossClient.completeMultipartUpload(completeMultipartUploadRequest);
System.out.println(completeMultipartUploadResult.getETag());
// 关闭OSSClient。
ossClient.shutdown();
return ResultBody.success();
}
@ApiOperation(value = "上传到阿里云oss")
@PostMapping("/oss")
public ResultBody oss(
@RequestPart("uploadFile") MultipartFile uploadFile, HttpServletRequest httpRequest)
throws Exception {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "yourEndpoint";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
String objectName = "exampledir/exampleobject.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 创建InitiateMultipartUploadRequest对象。
InitiateMultipartUploadRequest request =
new InitiateMultipartUploadRequest(bucketName, objectName);
// 如果需要在初始化分片时设置文件存储类型,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
// StorageClass.Standard.toString());
// request.setObjectMetadata(metadata);
// 初始化分片。
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
// 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。
String uploadId = upresult.getUploadId();
// partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。
List<PartETag> partETags = new ArrayList<PartETag>();
// 每个分片的大小,用于计算文件有多少个分片。单位为字节。
final long partSize = 1 * 1024 * 1024L; // 1 MB。
// 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
final File sampleFile = new File("D:\\localpath\\examplefile.txt");
long fileLength = sampleFile.length();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// 遍历分片上传。
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
InputStream instream = new FileInputStream(sampleFile);
// 跳过已经上传的分片。
instream.skip(startPos);
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(instream);
// 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。
uploadPartRequest.setPartSize(curPartSize);
// 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。
uploadPartRequest.setPartNumber(i + 1);
// 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。
partETags.add(uploadPartResult.getPartETag());
}
// 创建CompleteMultipartUploadRequest对象。
// 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// 如果需要在完成文件上传的同时设置文件访问权限,请参考以下示例代码。
// completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead);
// 完成上传。
CompleteMultipartUploadResult completeMultipartUploadResult =
ossClient.completeMultipartUpload(completeMultipartUploadRequest);
System.out.println(completeMultipartUploadResult.getETag());
// 关闭OSSClient。
ossClient.shutdown();
return ResultBody.success();
}
}
package com.mmc.pms.controller;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mmc.pms.common.ResultBody;
import com.mmc.pms.common.ResultEnum;
import com.mmc.pms.util.FileLoadUtil;
import com.mmc.pms.util.OssConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Author small @Date 2023/5/23 10:12 @Version 1.0
*/
@Api(tags = {"上传文件"})
@RestController
@RequestMapping("/upload")
public class UploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@ApiOperation(value = "上传到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/oss")
public ResultBody oss(
@RequestPart("uploadFile") MultipartFile uploadFile, HttpServletRequest request) {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
InputStream inputStream = null;
try {
inputStream = uploadFile.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
String oldName = uploadFile.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, inputStream);
ossClient.shutdown();
String filePath = "https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName;
JSONObject jsObj = new JSONObject();
jsObj.put("filePath", filePath);
return ResultBody.success(jsObj);
}
@ApiOperation(value = "上传多个文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/osses")
public ResultBody osses(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
List list = new LinkedList();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, inputStream);
// ossClient.shutdown();
// String filePath = "https://" + OssConstant.BUCKET + '.' +
// OssConstant.ENDPOINT + "/" +
// newName;
list.add("https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(list);
}
@ApiOperation(value = "上传视频文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/videoOss")
public ResultBody videoOss(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setRequestTimeoutEnabled(true);
clientBuilderConfiguration.setConnectionRequestTimeout(600000 * 20);
clientBuilderConfiguration.setConnectionTimeout(600000 * 20);
OSS ossClient =
new OSSClientBuilder()
.build(
OssConstant.ENDPOINT,
OssConstant.ACCESSKEYID,
OssConstant.ACCESSKEYSECRET,
clientBuilderConfiguration);
List list = new LinkedList();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 3) {
return ResultBody.error(ResultEnum.UPLOAD_VIDEO_ERROR);
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("视频名称:" + newName);
list.add("https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
}
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(list);
}
@ApiOperation(value = "上传视频文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/videoOsses")
public ResultBody videoOsses(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setRequestTimeoutEnabled(true);
clientBuilderConfiguration.setConnectionRequestTimeout(600000 * 20);
clientBuilderConfiguration.setConnectionTimeout(600000 * 20);
OSS ossClient =
new OSSClientBuilder()
.build(
OssConstant.ENDPOINT,
OssConstant.ACCESSKEYID,
OssConstant.ACCESSKEYSECRET,
clientBuilderConfiguration);
Map map = new HashMap();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 3) {
return ResultBody.error(ResultEnum.UPLOAD_VIDEO_ERROR);
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("视频名称:" + newName);
map.put(
"filePath",
"https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
map.put("fileName", oldName);
map.put("fileSize", file.getSize());
map.put("fileType", oldName.substring(oldName.lastIndexOf(".")).replace(".", ""));
}
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(map);
}
@ApiOperation(value = "上传图片文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/imgOss")
public ResultBody imgOss(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
List list = new LinkedList();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 1) {
return ResultBody.error(ResultEnum.UPLOAD_IMG_ERROR);
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("图片名称:" + newName);
list.add("https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
}
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(list);
}
@ApiOperation(value = "上传图片文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/singleImgOss")
public ResultBody singleImgOss(
@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request)
throws IOException {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
List list = new LinkedList();
if (uploadFile != null) {
if (uploadFile.getSize() / 1024 > 3096) {
return ResultBody.error("请上传小于3M的图片");
}
InputStream inputStream = null;
try {
inputStream = uploadFile.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 1) {
return ResultBody.error(ResultEnum.UPLOAD_IMG_ERROR);
}
String oldName = uploadFile.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("图片名称:" + newName);
list.add("https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(list);
}
@ApiOperation(value = "上传图片文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/imgOsses")
public ResultBody imgOsses(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
Map map = new HashMap();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 1) {
return ResultBody.error(ResultEnum.UPLOAD_IMG_ERROR);
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("图片名称:" + newName);
map.put(
"filePath",
"https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
map.put("fileName", oldName);
map.put("fileSize", file.getSize());
map.put("fileType", oldName.substring(oldName.lastIndexOf(".")).replace(".", ""));
}
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(map);
}
private byte[] readByte(final InputStream is) throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
BufferedOutputStream bos = new BufferedOutputStream(bas)) {
byte[] bytes = new byte[4096];
int size;
while ((size = bis.read(bytes)) != -1) {
bos.write(bytes, 0, size);
}
return bas.toByteArray();
}
}
@ApiOperation(value = "上传文档文件到阿里云oss")
@ApiImplicitParams({
@ApiImplicitParam(
paramType = "header",
name = "mmc-identity",
dataTypeClass = java.lang.String.class,
dataType = "String",
required = true,
value = "token"),
@ApiImplicitParam(
name = "uploadFile",
dataType = "MultipartFile",
dataTypeClass = org.springframework.web.multipart.MultipartFile.class,
required = true,
value = "文件"),
})
@PostMapping("/docOss")
public ResultBody docOss(
@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request)
throws IOException {
OSS ossClient =
new OSSClientBuilder()
.build(OssConstant.ENDPOINT, OssConstant.ACCESSKEYID, OssConstant.ACCESSKEYSECRET);
Map map = new HashMap();
if (uploadFile != null && uploadFile.length > 0) {
System.out.println("osses文件数量" + uploadFile.length);
for (int i = 0; i < uploadFile.length; i++) {
MultipartFile file = uploadFile[i];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
return ResultBody.error(e.getMessage());
}
try (final BufferedInputStream bis = new BufferedInputStream(inputStream)) {
// 校验
int typeNum = FileLoadUtil.checkFileType(FileLoadUtil.getType(bis));
if (typeNum != 2) {
return ResultBody.error(ResultEnum.UPLOAD_DOC_ERROR);
}
String oldName = file.getOriginalFilename();
String newName =
"file/"
+ UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
ossClient.putObject(OssConstant.BUCKET, newName, bis);
System.out.println("文档名称:" + newName);
map.put(
"filePath",
"https://" + OssConstant.BUCKET + '.' + OssConstant.ENDPOINT + "/" + newName);
map.put("fileName", oldName);
map.put("fileSize", file.getSize());
map.put("fileType", oldName.substring(oldName.lastIndexOf(".")).replace(".", ""));
}
}
}
ossClient.shutdown(); // 关流
return ResultBody.success(map);
}
/**
* 上传文件
*
* @param uploadFile
* @return
*/
@RequestMapping(value = "/local", method = RequestMethod.POST)
public ResultBody local(
@RequestParam(value = "uploadFile", required = false) MultipartFile[] uploadFile,
@RequestParam(value = "directory", required = false, defaultValue = "upload")
String directory,
HttpServletRequest request)
throws IOException {
return FileLoadUtil.bathCreateFile(directory, uploadFile);
}
/**
* 下载文件
*
* @param path
* @param response
* @throws IOException
*/
@RequestMapping(value = "/download/{path}", method = RequestMethod.GET)
public void getDownloadFile(@PathVariable("path") String path, HttpServletResponse response)
throws IOException {
response.setContentType("application/x-001");
path = FileLoadUtil.explainLoadPath(path);
ServletOutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(new File(path));
byte buffer[] = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
@RequestMapping(value = "/heart", method = RequestMethod.GET)
public ResultBody heart() {
return ResultBody.success("heart");
}
}
package com.mmc.pms.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.*;
import java.util.List;
/**
* @Author small @Date 2023/5/23 13:50 @Version 1.0
*/
public class JsonUtil {
public static void main(String[] args) {
String array = "[1,24,23]";
List<Integer> list = JSONArray.parseArray(array, Integer.class);
System.out.println(list.get(2));
}
/**
* 把Java对象转换成json字符串
*
* @param object 待转化为JSON字符串的Java对象
* @return json 串 or null
*/
public static String parseObjToJson(Object object) {
String string = null;
try {
string = JSONObject.toJSONString(object);
} catch (Exception e) {
// LOGGER.error(e.getMessage());
}
return string;
}
/**
* 将Json字符串信息转换成对应的Java对象
*
* @param json json字符串对象
* @param c 对应的类型
*/
public static <T> T parseJsonToObj(String json, Class<T> c) {
try {
JSONObject jsonObject = JSON.parseObject(json);
return JSON.toJavaObject(jsonObject, c);
} catch (Exception e) {
// LOGGER.error(e.getMessage());
}
return null;
}
/**
* 读取json文件
*
* @param fileName
* @return
*/
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 将JSON数据格式化并保存到文件中
*
* @param jsonData 需要输出的json数
* @param filePath 输出的文件地址
* @return
*/
public static boolean createJsonFile(Object jsonData, String filePath) {
String content =
JSON.toJSONString(
jsonData,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
// 标记文件生成是否成功
boolean flag = true;
// 生成json格式文件
try {
// 保证创建一个新文件
File file = new File(filePath);
if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
file.getParentFile().mkdirs();
}
if (file.exists()) { // 如果已存在,删除旧文件
file.delete();
}
file.createNewFile();
// 将格式化后的字符串写入文件
Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
write.write(content);
write.flush();
write.close();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
}
package com.mmc.pms.redis;
/**
* @Author small @Date 2023/5/23 13:49 @Version 1.0
*/
public class RedisConstant {
/** 验证码-key */
public static final String VERIFYCODEKEY = "verifyCode";
/** 电话号码-key */
public static final String PHONENUMKEY = "phoneNum";
/** 当天用户量统计-key */
public static final String ACTIVE_USER_TOTAL_COUNT_TODAY = "active_user_total_count_today";
/** 后台-当天用户量统计-key */
public static final String ADMIN_ACTIVE_COUNT_TODAY = "admin_active_count_today";
/** 云享飞-当天用户量统计-key */
public static final String YXF_ACTIVE_COUNT_TODAY = "yxf_active_count_today";
/** 云飞手-当天用户量统计-key */
public static final String YFS_ACTIVE_COUNT_TODAY = "yfs_active_count_today";
/** 云仓-当天用户量统计-key */
public static final String YC_ACTIVE_COUNT_TODAY = "yc_active_count_today";
/** 登录信息token前缀 */
public static final String LOGING_TOKEN_BEFORE = "CLOUD-SHARED-FLIGHT-USERID@";
/**
* token黑名单-key
*
* @param userId
* @return
*/
/** 实名认证 redis 的键 */
public static final String REALNAMEREDISKEY = "realName";
/** token失效 */
public static final String DISABLE_TOKEN = "DISABLE-TOKEN";
/**
* 分片上传的key
*
* @param userId
* @return
*/
public static final String PART_UPLOAD = "UPLOAD_PART_";
/** 飞手端-假数据-分页信息-可以 */
public static final String FLYER_DUMMY_DATA_PAGE = "FLYER_DUMMY_DATA_PAGE";
/** token失效列表的key */
public static final String DISABLE_TOKEN_LIST = "DISABLE_TOKEN_LIST";
/** 无人机城的订单状态 */
public static final String UAV_MALL_ORDER_STATUS = "UAV_MALL_ORDER_STATUS";
/** 无人机城的快递公司编码 */
public static final String UAV_MALL_EXP_COM = "UAV_MALL_EXP_COM";
/** 无人机城的快递状态码 */
public static final String UAV_MALL_EXP_STATUS = "UAV_MALL_EXP_STATUS";
/**
* 微信access_token
*
* @param userId
* @return
*/
public static final String WX_ACCESS_TOKEN_BEFORE = "WX_ACCESS_TOKEN_";
public static final String REPO_SEND_PAY_MESSAGE = "REPO_ORDER_REMIND_PAY_";
public static final String FLYER_PUBLIC_DEFAULT_NAME = "FLYER_PUBLIC_DEFAULT_NAME";
public static final String EVALUATION = "EVALUATION";
public static final String FLYER_DUMMY_DATA = "FLYER_DUMMY_DATA_KEY";
public static final String UAV_DUMMY_DATA = "UAV_DUMMY_DATA_KEY";
/** tagInfoAllot表的缓存key */
public static final String TAGINFOALLOT_QUESTALL = "csf-service-system:tagInfoAllot:questAll";
public static String getDisableTokenKey(String accountId, String roleId, String tokenType) {
StringBuffer key = new StringBuffer();
key.append(RedisConstant.DISABLE_TOKEN);
key.append("_ROLE_");
key.append(roleId);
key.append("_");
key.append(accountId);
return key.toString();
}
/**
* 生成唯一的分片上传key
*
* @param uploadId
* @return
*/
public static String createPartUploadKey(String uploadId) {
StringBuffer key = new StringBuffer();
key.append(uploadId);
return key.toString();
}
/** 生成微信api的access_token的key */
public static String createWxToken(String wxAppid) {
StringBuffer key = new StringBuffer();
key.append(RedisConstant.WX_ACCESS_TOKEN_BEFORE);
key.append(wxAppid);
return key.toString();
}
/** 表单重复提交key */
public static String createRepeatKey(String token, String url, String params) {
StringBuffer key = new StringBuffer();
key.append(token);
key.append(url);
key.append(params);
return key.toString();
}
public static String createRepeatKey(String token, String url) {
return RedisConstant.createRepeatKey(token, url, "");
}
/** 登录缓存信息 */
public static String createLoginCacheKey(String tokenType, Integer id) {
StringBuffer key = new StringBuffer();
key.append(tokenType);
key.append("_");
key.append(id);
return key.toString();
}
/** 每位账号的的token的key的前缀 */
public static String tokenPreFix(String tokenType, String roleId) {
StringBuffer key = new StringBuffer();
key.append(tokenType);
key.append("_ROLE_");
key.append(roleId);
key.append("_");
return key.toString();
}
/** 每位账号的token保存的key */
public static String createLoginTokenKey(String tokenType, String roleId, String accountId) {
StringBuffer key = new StringBuffer();
key.append(RedisConstant.tokenPreFix(tokenType, roleId));
key.append(accountId);
return key.toString();
}
public static String createRepoOrderOver(Integer orderInfoId) {
StringBuffer key = new StringBuffer();
key.append(RedisConstant.REPO_SEND_PAY_MESSAGE);
key.append(orderInfoId);
return key.toString();
}
public static String getLockKey(String userId, String tokenType, String path) {
StringBuffer sb = new StringBuffer();
sb.append(userId);
sb.append("_");
sb.append(tokenType);
sb.append("_");
sb.append(path);
return sb.toString();
}
public static String createInspection(Integer id) {
StringBuffer key = new StringBuffer();
key.append(RedisConstant.EVALUATION);
key.append(id);
return key.toString();
}
public static String accessTokenKey(String clientId, Integer roleId, String grantType) {
StringBuilder key = new StringBuilder();
key.append("OAUTH_");
key.append(clientId);
key.append("_");
key.append(roleId);
key.append("_");
key.append(grantType);
return key.toString();
}
public static String getCompanyChildKey(Integer companyId) {
StringBuilder key = new StringBuilder();
key.append("company_cache:");
key.append(companyId);
return key.toString();
}
public static String getXEAccessTokenKey() {
StringBuilder key = new StringBuilder();
key.append("XE_ACCESS_TOKEN");
return key.toString();
}
}
package com.mmc.pms.util;
import com.mmc.pms.common.ResultBody;
import com.mmc.pms.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Author small @Date 2023/5/23 10:16 @Version 1.0
*/
@Slf4j
public class FileLoadUtil {
/**
* 批量生成文件
*
* @throws IOException
* @throws IllegalStateException
*/
public static ResultBody bathCreateFile(String directory, MultipartFile[] files)
throws IllegalStateException, IOException {
if (files == null || files.length == 0) {
return ResultBody.error(
ResultEnum.FILE_UPLOAD_NULL_ERROR.getResultCode(),
ResultEnum.FILE_UPLOAD_NULL_ERROR.getResultMsg());
}
List<String> downloadPaths = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
String filename = FileLoadUtil.createNewFileName(files[i].getOriginalFilename());
// 创建新路径
String newFileDir = FileLoadUtil.createFileDirctory(directory);
// 创建文件对象
File uploadFile = new File(newFileDir + filename);
if (!uploadFile.getParentFile().exists()) {
uploadFile.getParentFile().mkdirs();
}
while (uploadFile.exists()) { // 文件名重复
filename = filename + "(" + i + ")";
uploadFile = new File(newFileDir + filename);
i++;
}
uploadFile.createNewFile();
files[i].transferTo(uploadFile);
downloadPaths.add(FileLoadUtil.createDownLoadPath(directory, filename));
}
return ResultBody.success(downloadPaths);
}
/**
* 文件名
*
* @param originalFilename
* @return
*/
public static String createNewFileName(String originalFilename) {
int i = originalFilename.lastIndexOf('.');
String endWith = "";
StringBuffer sb = new StringBuffer();
if (i >= 0) {
endWith = originalFilename.substring(i);
}
sb.append(System.currentTimeMillis());
sb.append(endWith);
return sb.toString();
}
/** 文件夹路径 */
public static String createFileDirctory(String directory) {
return FileServletConstant.MOUNTVOLUME
+ directory
+ File.separator
+ TDateUtil.getCurrentDateByType("yyyyMMdd")
+ File.separator;
}
/** 解析下载路径 */
public static String explainLoadPath(String path) {
return FileServletConstant.MOUNTVOLUME + path.replaceAll("@", FileServletConstant.separator);
}
/** 生成下载地址 */
public static String createDownLoadPath(String directory, String filename) {
return FileServletConstant.DOWNLOADPATH
+ directory
+ "@"
+ TDateUtil.getCurrentDateByType("yyyyMMdd")
+ "@"
+ filename;
}
/**
* 判断文件大小
*
* @param len
* @param size
* @param unit
*/
public static boolean checkFileSize(Long len, int size, String unit) {
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
/**
* 将文件头转换成16进制字符串
*
* @return 16进制字符串
*/
private static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 得到文件头
*
* @return 文件头
* @throws IOException
*/
private static String getFileContent(InputStream is) throws IOException {
final int len = 20;
byte[] b = new byte[len];
final boolean isMark = is.markSupported();
if (isMark) {
is.mark(len);
}
try {
is.read(b, 0, len);
} catch (IOException e) {
log.warn("读取文件头信息失败: ", e);
throw e;
} finally {
if (isMark) {
is.reset();
}
}
return bytesToHexString(b);
}
public static FileTypeConstant getType(InputStream is) throws IOException {
return getType(getFileContent(is));
}
public static FileTypeConstant getType(final byte[] bytes) throws IOException {
return getType(bytesToHexString(bytes));
}
public static FileTypeConstant getType(String fileHead) throws IOException {
if (fileHead == null || fileHead.length() == 0) {
return null;
}
fileHead = fileHead.toUpperCase();
FileTypeConstant[] fileTypes = FileTypeConstant.values();
for (FileTypeConstant type : fileTypes) {
String s = type.getValue().toUpperCase();
if (fileHead.contains(type.getValue().toUpperCase())) {
return type;
}
}
return null;
}
public static Integer checkFileType(FileTypeConstant value) {
Integer type = 4; // 其他
// 图片
FileTypeConstant[] pics = {
FileTypeConstant.JPEG, FileTypeConstant.PNG, FileTypeConstant.BMP, FileTypeConstant.GIF
};
FileTypeConstant[] docs = {
FileTypeConstant.PST,
FileTypeConstant.XLS_DOC,
FileTypeConstant.XLSX_DOCX,
FileTypeConstant.WPS,
FileTypeConstant.PDF,
FileTypeConstant.PPTX_DOCX
};
FileTypeConstant[] videos = {
FileTypeConstant.AVI,
FileTypeConstant.RAM,
FileTypeConstant.RM,
FileTypeConstant.MPG,
FileTypeConstant.MOV,
FileTypeConstant.ASF,
FileTypeConstant.MP4,
FileTypeConstant.FLV,
FileTypeConstant.MID
};
// 图片
for (FileTypeConstant fileType : pics) {
if (fileType.equals(value)) {
type = 1;
}
}
// 文档
for (FileTypeConstant fileType : docs) {
if (fileType.equals(value)) {
type = 2;
}
}
// 视频
for (FileTypeConstant fileType : videos) {
if (fileType.equals(value)) {
type = 3;
}
}
return type;
}
}
package com.mmc.pms.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
/**
* @Author small @Date 2023/5/23 10:24 @Version 1.0
*/
@Component
public class FileServletConstant {
public static String MOUNTVOLUME;
public static String separator;
public static String DOWNLOADPATH; // 下载地址
public FileServletConstant(
@Value("${mount.directory}") String mountVolume,
@Value("${mmcflying.download.path}") String downloadPath) {
if (File.separator.equals("\\")) {
separator = "\\\\";
} else {
separator = File.separator;
}
MOUNTVOLUME = mountVolume.replaceAll("@", separator);
DOWNLOADPATH = downloadPath;
}
}
package com.mmc.pms.util;
/**
* @Author small @Date 2023/5/23 10:17 @Version 1.0
*/
public enum FileTypeConstant {
/** JEPG. */
JPEG("FFD8FF"),
/** PNG. */
PNG("89504E47"),
/** Windows Bitmap. */
BMP("424D"),
/** GIF. */
GIF("47494638"),
/** Outlook (pst). */
PST("2142444E"),
/** MS Word/Excel. */
XLS_DOC("D0CF11E0"),
XLSX_DOCX("504B030414000600080000002100"),
PPTX_DOCX("504B03040A0000000000874EE240000000000000"),
XLSX_DOC("504B03041400000008000A52F64E926EBD1F8501"),
/** WPS文字wps、表格et、演示dps都是一样的 */
WPS("D0CF11E0A1B11AE10000"),
/** Adobe Acrobat. */
PDF("255044462D312E"),
/** Wave. */
WAV("57415645"),
/** AVI. */
AVI("41564920"),
/** Real Audio. */
RAM("2E7261FD"),
/** Real Media. */
RM("2E524D46"),
/** MPEG (mpg). */
MPG("000001BA"),
/** Quicktime. */
MOV("6D6F6F76"),
/** Windows Media. */
ASF("3026B2758E66CF11"),
/** MIDI. */
MID("4D546864"),
/** MP4. */
// MP4("00000020667479706"),
// mp4("00000018667479706D70"),
MP4("667479706"),
/** MP3. */
MP3("49443303000000002176"),
/** FLV. */
FLV("464C5601050000000900");
private String value = "";
/**
* Constructor.
*
* @param value
*/
private FileTypeConstant(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package com.mmc.pms.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Author small @Date 2023/5/23 10:26 @Version 1.0
*/
@Component
public class OssConstant {
public static String ENDPOINT;
public static String ACCESSKEYID;
public static String ACCESSKEYSECRET;
public static String BUCKET;
public OssConstant(
@Value("${aliyun.oss.endpoint}") String endPoint,
@Value("${aliyun.oss.access-key-id}") String accessKeyId,
@Value("${aliyun.oss.access-key-secret}") String accessKeySecret,
@Value("${aliyun.oss.bucket}") String bucket) {
ENDPOINT = endPoint;
ACCESSKEYID = accessKeyId;
ACCESSKEYSECRET = accessKeySecret;
BUCKET = bucket;
}
}
package com.mmc.pms.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Author small @Date 2023/5/23 13:48 @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PartUploadInfo implements Serializable {
private static final long serialVersionUID = 4138719631627565554L;
private String uploadId;
private String bucketName;
private String objectName;
}
package com.mmc.pms.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Author small @Date 2023/5/23 10:25 @Version 1.0
*/
public class TDateUtil {
public static final String ONE_WEEK = "oneweek";
public static final String ONE_MONTH = "onemonth";
public static final String THREE_MONTH = "threemonth";
public static final String SIX_MONTH = "sixmonth";
public static final String ONE_YEAR = "oneyear";
public static String getCurrentDate() {
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 设置日期格式
String date = df.format(new Date()); // new Date()为获取当前系统时间
return date;
}
public static String getCurrentDateByType(String format) {
SimpleDateFormat df = new SimpleDateFormat(format); // 设置日期格式
String date = df.format(new Date()); // new Date()为获取当前系统时间
return date;
}
public static String getCurrentDateMidd() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
String date = df.format(new Date()); // new Date()为获取当前系统时间
return date;
}
public static Date getDate(String str, String format) {
Date date = null;
try {
SimpleDateFormat df = new SimpleDateFormat(format); // 设置日期格式
// String dates=df.format(new Date());// new Date()为获取当前系统时间
date = df.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/** date类型转字符串 */
public static String getDateStr(Date date, String type) {
SimpleDateFormat format = new SimpleDateFormat(type);
String s = format.format(date);
return s;
}
/** 根据日期获得随机数 */
public static Integer getDateRandom(Date date, String format, int count) {
String code = "";
for (int i = 0; i < count; i++) {
code = code + (int) (Math.random() * 9);
}
code = TDateUtil.getDateStr(date, format) + code;
return Integer.parseInt(code);
}
/**
* 10位数的秒转日期字符
*
* @param mss
* @return
*/
public static Date dateFromSecond(long sceondTime) {
return new Date(sceondTime * 1000);
}
/**
* 10位数的秒转日期字符
*
* @param mss
* @return
*/
public static String dateFromSecondStr(long sceondTime) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(sceondTime * 1000));
}
/**
* 秒转时分秒
*
* @param secondTime
* @return
*/
public static String hmsFromSecond(Integer secondTime) {
Integer hour = secondTime / 60 / 60;
Integer minutes = secondTime / 60 % 60;
Integer remainingSeconds = secondTime % 60;
return (hour + "h" + minutes + "min" + remainingSeconds + "s");
}
public static String hmsFromSecondFormat(long secondTime) {
long day = secondTime / 60 / 60 / 24;
long hour = secondTime / 60 / 60 % 24;
long minutes = secondTime / 60 % 60;
long remainingSeconds = secondTime % 60;
if (day > 0) {
return (day + "天" + hour + "小时" + minutes + "分" + remainingSeconds + "秒");
}
return (hour + "小时" + minutes + "分" + remainingSeconds + "秒");
}
/**
* 两个日期的相差秒数
*
* @param maxDate
* @param minDate
* @return
*/
public static long calLastedTime(Date maxDate, Date minDate) {
long a = maxDate.getTime();
long b = minDate.getTime();
long c = (a - b) / 1000;
return c;
}
/** 获取某个月的月底最后一天的时间 */
public static Date getMonthLatestDay(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
Date dates = getDate(last, "yyyy-MM-dd");
return dates;
}
/** 某个时间 加N天 */
public static Date nextNumDay(Date d, int num) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
Date now = d;
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(Calendar.DAY_OF_MONTH, num);
String last = format.format(calendar.getTime());
date = getDate(last, "yyyy-MM-dd");
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/**
* 某天个时间加 N 小时
*
* @param now
* @param num
* @return
*/
public static Date addHourTime(Date now, int num) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(Calendar.HOUR, num);
String last = format.format(calendar.getTime());
date = getDate(last, "yyyy-MM-dd HH:mm:ss");
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/** 某个时间加n个月加n天(负数为减) */
@SuppressWarnings("static-access")
public static Date getMonthNDayN(Date date, int month, int day) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date news = null;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, month);
calendar.add(calendar.DATE, day);
String last = format.format(calendar.getTime());
news = getDate(last, "yyyy-MM-dd");
} catch (Exception e) {
e.printStackTrace();
}
return news;
}
/** 时间戳-计算小时 */
public static long getDistanceTime(long time1, long time2) {
long diff = 0;
long day = 0;
long hour = 0;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
return hour;
}
/**
* 两个时间之间相差距离多少天
*
* @param one 时间参数 1:
* @param two 时间参数 2:
* @return 相差天数
*/
public static int distanceDays(Date one, Date two) {
int days = 0;
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
days = new Long(diff / (1000 * 60 * 60 * 24)).intValue();
return days;
}
public static Date nextNumDateTime(Date d, int num) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
Date now = d;
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(Calendar.DAY_OF_MONTH, num);
String last = format.format(calendar.getTime());
date = getDate(last, "yyyy-MM-dd HH:mm:ss");
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public static String createYearWeek(String startStr, String endStr) {
if (startStr == null || "".equals(startStr) || endStr == null || "".equals(endStr)) {
return "起止日期不能为空";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date start = null;
Date end = null;
Date startDate;
Date endDate;
int dayOfWeek;
boolean goOn = true;
int no = 0;
try {
start = sdf.parse(startStr);
end = sdf.parse(endStr);
} catch (ParseException e) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
try {
start = simpleDateFormat.parse(startStr);
end = simpleDateFormat.parse(endStr);
} catch (ParseException pe) {
pe.printStackTrace();
}
}
if (start.compareTo(end) > -1) {
return "结束日期必须大于开始日期";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
List<Map<String, String>> weekList = new ArrayList<>();
if (dayOfWeek > 1 && dayOfWeek < 7) {
do {
startDate = start;
calendar.add(Calendar.DATE, (8 - dayOfWeek));
endDate = calendar.getTime();
no += 1;
Map<String, String> map = new HashMap<>();
map.put("startOfWeek", sdf.format(startDate));
map.put("weekNo", no + "");
if (endDate.compareTo(end) < 0) {
map.put("endOfWeek", sdf.format(endDate));
weekList.add(map);
calendar.add(Calendar.DATE, 1);
start = calendar.getTime();
dayOfWeek = 2;
} else {
map.put("endOfWeek", sdf.format(end));
weekList.add(map);
goOn = false;
}
} while (goOn);
} else {
no += 1;
startDate = start;
if (dayOfWeek == 1) {
endDate = start;
} else {
calendar.add(Calendar.DATE, 1);
endDate = calendar.getTime();
}
Map<String, String> map = new HashMap<>();
map.put("startOfWeek", sdf.format(startDate));
map.put("endOfWeek", sdf.format(endDate));
map.put("weekNo", no + "");
weekList.add(map);
calendar.add(Calendar.DATE, 1);
start = calendar.getTime();
do {
startDate = start;
calendar.add(Calendar.DATE, 6);
endDate = calendar.getTime();
no += 1;
map = new HashMap<>();
map.put("startOfWeek", sdf.format(startDate));
map.put("weekNo", no + "");
if (endDate.compareTo(end) < 0) {
map.put("endOfWeek", sdf.format(endDate));
weekList.add(map);
calendar.add(Calendar.DATE, 1);
start = calendar.getTime();
} else {
map.put("endOfWeek", sdf.format(end));
weekList.add(map);
goOn = false;
}
} while (goOn);
}
return weekList.toString();
}
/**
* 获取起止日期
*
* @param sdf 需要显示的日期格式
* @param date 需要参照的日期
* @param n 最近n周
* @param option 0 开始日期;1 结束日期
* @param k 0 包含本周 1 不包含本周
* @return
*/
public static String getFromToDate(SimpleDateFormat sdf, Date date, int n, int option, int k) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int offset = 0 == option ? 1 - dayOfWeek : 7 - dayOfWeek;
int amount = 0 == option ? offset - (n - 1 + k) * 7 : offset - k * 7;
calendar.add(Calendar.DATE, amount);
return sdf.format(calendar.getTime());
}
/**
* 根据当前日期获得最近n周的日期区间(包含本周)
*
* @param n
* @param sdf
* @return
*/
public static String getNWeekTimeInterval(int n, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format); // 设置日期格式
String beginDate = getFromToDate(sdf, new Date(), n, 0, 0);
String endDate = getFromToDate(sdf, new Date(), n, 1, 0);
return beginDate + "," + endDate;
}
/**
* 根据当前日期获得最近n周的日期区间(不包含本周)
*
* @param n
* @param sdf
* @return
*/
public static String getNWeekTimeIntervalTwo(int n, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format); // 设置日期格式
String beginDate = getFromToDate(sdf, new Date(), n, 0, 1);
String endDate = getFromToDate(sdf, new Date(), n, 1, 1);
return beginDate + "," + endDate;
}
/**
* 根据当前日期获得本周的日期区间(本周周一和周日日期)
*
* @param sdf
* @return
*/
public static String getThisWeekTimeInterval(String format) {
return getNWeekTimeInterval(1, format);
}
/**
* 根据当前日期获得上周的日期区间(上周周一和周日日期)
*
* @param sdf
* @return
*/
public static String getLastWeekTimeInterval(String format) {
return getNWeekTimeIntervalTwo(1, format);
}
/**
* 获取某个日期最近一个的星期日
*
* @return
*/
public static Date getLatestWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
Date endDate = TDateUtil.nextNumDay(date, w * -1);
return endDate;
}
/**
* 获取N周的星期一的日期(正加负减)
*
* @param date
* @return
*/
public static Date getMinMonday(Date date, int weekNum) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
Date endDate = TDateUtil.nextNumDay(date, w * -1);
Date startDate = TDateUtil.nextNumDay(endDate, (weekNum * 7) + 1);
return startDate;
}
/** 获取某个月加几个月后一号的日期 */
@SuppressWarnings("static-access")
public static Date getAddMonThDay(Date date, int i) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.MONTH, i);
calendar.set(Calendar.DAY_OF_MONTH, 1);
String last = format.format(calendar.getTime());
date = getDate(last, "yyyy-MM-dd");
return date;
}
/** 某个月最后一天 */
public static Date getAnyMonthLastDay(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
date = getDate(last, "yyyy-MM-dd");
return date;
}
public static Date getDate(Date date, String type) {
SimpleDateFormat format = new SimpleDateFormat(type);
String s = format.format(date);
return getDate(s, type);
}
/** 获取去年今天的日期 */
public static Date getLastYearTodayDate() {
Calendar instance = Calendar.getInstance();
instance.add(Calendar.YEAR, -1);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String s = format.format(instance.getTime());
return getDate(s, "yyyy-MM-dd");
}
/**
* 获取昨天的日期
*
* @param type
* @return
*/
public static String getYesterdayDateByType(String type) {
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DAY_OF_MONTH, -1);
Date time = instance.getTime();
SimpleDateFormat format = new SimpleDateFormat(type);
return format.format(time);
}
/** 判断两个时间是不是在同一个月 */
public static boolean isSameMonth(Date date1, Date date2) {
Calendar c = Calendar.getInstance();
c.setTime(date1);
int month1 = c.get(Calendar.MONTH);
c.setTime(date2);
int month2 = c.get(Calendar.MONTH);
if (month1 == month2) {
return true;
}
return false;
}
/**
* 间隔天数
*
* @param startTime
* @param endTime
* @return
*/
public static int isolateDayNum(String startTime, String endTime) {
Date startDate = getDate(startTime, "yyyy-MM-dd");
Date endDate = getDate(endTime, "yyyy-MM-dd");
long differentMillis = endDate.getTime() - startDate.getTime();
long dayNum = differentMillis / (1000 * 60 * 60 * 24);
return (int) dayNum;
}
/**
* 获取某月最后一天的时间
*
* @param yearMonth
* @return
*/
public static String getLastDateTimeOfMonth(String yearMonth) {
SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM");
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar instance = Calendar.getInstance();
try {
Date parse = format0.parse(yearMonth);
instance.setTime(parse);
instance.set(Calendar.DAY_OF_MONTH, instance.getActualMaximum(Calendar.DAY_OF_MONTH));
instance.set(Calendar.HOUR_OF_DAY, 23);
instance.set(Calendar.MINUTE, 59);
instance.set(Calendar.SECOND, 59);
String format = format1.format(instance.getTime());
return format;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Date getStrToDate(String str) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
Date date = null;
try {
if (str == null) {
date = null;
} else {
date = dateFormat.parse(str);
}
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static int getStageByDate(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
// 当前时间
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String format = dateFormat.format(date);
try {
Date currentTime = dateFormat.parse(format);
Date parse1 = dateFormat.parse("05:00:00");
Date parse2 = dateFormat.parse("11:00:00");
Date parse3 = dateFormat.parse("17:00:00");
Date parse4 = dateFormat.parse("00:00:00");
// A:05:00-11:00 | B:11:00-17:00 | C:00:00-05:00,17:00-00:00
if (currentTime.after(parse4) && currentTime.before(parse1)) {
return 3;
} else if (currentTime.after(parse1) && currentTime.before(parse2)) {
return 1;
} else if (currentTime.after(parse2) && currentTime.before(parse3)) {
return 2;
} else if (currentTime.after(parse3) && currentTime.after(parse4)) {
return 4;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static String getCurrentYear() {
Calendar date = Calendar.getInstance();
String year = String.valueOf(date.get(Calendar.YEAR));
return year;
}
}
......@@ -20,4 +20,17 @@ springfox:
enabled: false
enabled: true #开启文档
aliyun:
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
access-key-id: LTAI4FzCpyrA33PegnxWS6XV
access-key-secret: ILuNh3zJfRjg3iARSipMWBKCjglz3u
bucket: pad-video-x
mmcflying:
download:
path: /ossservlet/upload/download/
mount:
directory: D:@javaVolume@
......@@ -20,4 +20,17 @@ springfox:
enabled: false
enabled: true #开启文档
aliyun:
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
access-key-id: LTAI4FzCpyrA33PegnxWS6XV
access-key-secret: ILuNh3zJfRjg3iARSipMWBKCjglz3u
bucket: pad-video-x
mmcflying:
download:
path: /ossservlet/upload/download/
mount:
directory: D:@javaVolume@
......@@ -19,3 +19,16 @@ springfox:
swagger-ui:
enabled: false
enabled: true #开启文档
aliyun:
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
access-key-id: LTAI4FzCpyrA33PegnxWS6XV
access-key-secret: ILuNh3zJfRjg3iARSipMWBKCjglz3u
bucket: pad-video-x
mmcflying:
download:
path: /ossservlet/upload/download/
mount:
directory: D:@javaVolume@
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论