Commit 5e4c2459 authored by daniel's avatar daniel

fix(oss): oss接口优化

parent 0c5b20c0
......@@ -70,6 +70,14 @@ public class SecurityInterceptor extends JService implements HandlerInterceptor
return true;
}
// /gk/ 和 /easy/ 路径要求session登录
if ((uri.startsWith("/gk/") || uri.contains("easy")) && request.getSession().getAttribute("user") == null) {
response.sendRedirect(domain + "auth_no");
return false;
}
// 小程序请求放行(小程序没有session)
String userAgent = request.getHeader("user-agent");
if (userAgent != null) {
......@@ -79,12 +87,6 @@ public class SecurityInterceptor extends JService implements HandlerInterceptor
}
}
// /gk/ 和 /easy/ 路径要求session登录
if ((uri.startsWith("/gk/") || uri.contains("easy")) && request.getSession().getAttribute("user") == null) {
response.sendRedirect(domain + "auth_no");
return false;
}
if (annotation != null) {
// 已登录的用户跳过sign校验
if (request.getSession().getAttribute("user") != null) {
......
......@@ -42,31 +42,22 @@ public class AliOssUtil {
* @param objectName 文件名
* @return oss 的完整地址
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
public String upload(byte[] bytes, String objectName) throws IOException {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
log.error("OSS上传失败, objectName:{}, errorCode:{}, errorMessage:{}, requestId:{}, hostId:{}",
objectName, oe.getErrorCode(), oe.getErrorMessage(), oe.getRequestId(), oe.getHostId());
throw new IOException("OSS上传失败: " + oe.getErrorMessage(), oe);
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
log.error("OSS客户端异常, objectName:{}, errorMessage:{}", objectName, ce.getMessage(), ce);
throw new IOException("OSS客户端异常: " + ce.getMessage(), ce);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
return "https://" + bucketName + "." + endpoint + "/" + objectName;
}
......@@ -83,17 +74,10 @@ public class AliOssUtil {
ossClient.deleteObject(bucketName, objectName);
log.info("文件删除成功: {}/{}", bucketName, objectName);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
log.error("OSS删除失败, objectName:{}, errorCode:{}, errorMessage:{}, requestId:{}, hostId:{}",
objectName, oe.getErrorCode(), oe.getErrorMessage(), oe.getRequestId(), oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
log.error("OSS客户端异常(删除), objectName:{}, errorMessage:{}", objectName, ce.getMessage(), ce);
} finally {
if (ossClient != null) {
ossClient.shutdown();
......
......@@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
@RestController
......@@ -59,6 +60,10 @@ public class CommonController {
}
// 文件大小限制:10MB
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;
final private AliOssUtil aliOssUtil;
@PostMapping("/upload")
......@@ -67,21 +72,21 @@ public class CommonController {
try {
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
// 检查文件名中是否包含点号
if (originalFilename == null || originalFilename.trim().isEmpty()) {
return Result.fail().setMsg("文件名不能为空");
}
if (file.getSize() > MAX_FILE_SIZE) {
return Result.fail().setMsg("文件大小不能超过10MB");
}
int lastIndex = originalFilename.lastIndexOf(".");
if (lastIndex == -1) {
// 如果没有后缀名,直接返回报错信息
return Result.fail().setMsg("上传的文件没有后缀名,请检查文件");
}
String extension = originalFilename.substring(lastIndex).toLowerCase();
// 检查文件扩展名是否允许
if (!ALLOWED_FILE_TYPES.containsKey(extension)) {
return Result.fail().setMsg("不允许上传该文件类型,请检查文件");
}
// 检查文件魔数
if (!checkFileMagicNumber(file.getBytes(), extension)) {
if (!checkFileMagicNumber(file, extension)) {
return Result.fail().setMsg("文件类型与扩展名不符,请检查文件");
}
String objectName = UUID.randomUUID() + extension;
......@@ -94,7 +99,8 @@ public class CommonController {
log.info("文件上传名: {} 保存的文件名:{}", originalFilename,filePath);
return Result.success().setContent(filePath);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
log.error("文件上传失败, originalFilename:{}, folder:{}, cmptId:{}, fileSize:{}, error:{}",
file.getOriginalFilename(), folder, cmptId, file.getSize(), e.getMessage(), e);
}
return Result.fail().setMsg("文件上传失败");
}
......@@ -104,7 +110,12 @@ public class CommonController {
public Result<?> uploadWithName(@RequestPart @RequestParam("file") MultipartFile file, @RequestParam(value = "folder", defaultValue = "") String folder,@RequestParam(value = "fileName") String fileName) {
try {
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
if (originalFilename == null || originalFilename.trim().isEmpty()) {
return Result.fail().setMsg("文件名不能为空");
}
if (file.getSize() > MAX_FILE_SIZE) {
return Result.fail().setMsg("文件大小不能超过10MB");
}
int lastIndex = originalFilename.lastIndexOf(".");
if (lastIndex == -1) {
return Result.fail().setMsg("上传的文件没有后缀名,请检查文件");
......@@ -113,7 +124,7 @@ public class CommonController {
if (!ALLOWED_FILE_TYPES.containsKey(extension)) {
return Result.fail().setMsg("不允许上传该文件类型,请检查文件");
}
if (!checkFileMagicNumber(file.getBytes(), extension)) {
if (!checkFileMagicNumber(file, extension)) {
return Result.fail().setMsg("文件类型与扩展名不符,请检查文件");
}
String objectName = fileName;
......@@ -124,7 +135,8 @@ public class CommonController {
log.info("文件上传名: {} 保存的文件名:{}", originalFilename,filePath);
return Result.success().setContent(filePath);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
log.error("文件上传失败, originalFilename:{}, fileName:{}, folder:{}, fileSize:{}, error:{}",
file.getOriginalFilename(), fileName, folder, file.getSize(), e.getMessage(), e);
}
return Result.fail().setMsg("文件上传失败");
}
......@@ -141,7 +153,6 @@ public class CommonController {
if (originalFilename == null || originalFilename.isEmpty()) {
return Result.fail().setMsg("文件名不能为空");
}
assert originalFilename != null;
int lastIndex = originalFilename.lastIndexOf(".");
if (lastIndex == -1) {
return Result.fail().setMsg("上传的文件没有后缀名,请检查文件");
......@@ -150,7 +161,7 @@ public class CommonController {
if (!ALLOWED_FILE_TYPES.containsKey(extension)) {
return Result.fail().setMsg("不允许上传该文件类型,请检查文件");
}
if (!checkFileMagicNumber(file.getBytes(), extension)) {
if (!checkFileMagicNumber(file, extension)) {
return Result.fail().setMsg("文件类型与扩展名不符,请检查文件");
}
String objectName = "micro/" +gCmptId+ "_cmptId/mianze.png";
......@@ -158,7 +169,8 @@ public class CommonController {
log.info("文件上传名: {} 保存的文件名:{}", originalFilename,filePath);
return Result.success().setContent(filePath);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
log.error("参赛声明上传失败, originalFilename:{}, gCmptId:{}, fileSize:{}, error:{}",
file.getOriginalFilename(), gCmptId, file.getSize(), e.getMessage(), e);
}
return Result.fail().setMsg("文件上传失败");
}
......@@ -175,7 +187,6 @@ public class CommonController {
if (originalFilename == null || originalFilename.isEmpty()) {
return Result.fail().setMsg("文件名不能为空");
}
assert originalFilename != null;
int lastIndex = originalFilename.lastIndexOf(".");
if (lastIndex == -1) {
return Result.fail().setMsg("上传的文件没有后缀名,请检查文件");
......@@ -184,7 +195,7 @@ public class CommonController {
if (!ALLOWED_FILE_TYPES.containsKey(extension)) {
return Result.fail().setMsg("不允许上传该文件类型,请检查文件");
}
if (!checkFileMagicNumber(file.getBytes(), extension)) {
if (!checkFileMagicNumber(file, extension)) {
return Result.fail().setMsg("文件类型与扩展名不符,请检查文件");
}
String objectName = "micro/"+ gCmptId+"_cmptId/" + gCmptId+ "_"+roadId+".png";
......@@ -192,25 +203,37 @@ public class CommonController {
log.info("文件上传名: {} 保存的文件名:{}", originalFilename,filePath);
return Result.success().setContent(filePath);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
log.error("选号背景上传失败, originalFilename:{}, gCmptId:{}, roadId:{}, fileSize:{}, error:{}",
file.getOriginalFilename(), gCmptId, roadId, file.getSize(), e.getMessage(), e);
}
return Result.fail().setMsg("文件上传失败");
}
/**
* 检查文件的魔数是否与扩展名匹配
* @param fileBytes 文件字节数组
* @param extension 文件扩展名
* @return 如果匹配返回 true,否则返回 false
* 检查文件的魔数是否与扩展名匹配(只读取文件头字节,避免加载整个文件)
*/
private boolean checkFileMagicNumber(byte[] fileBytes, String extension) {
private boolean checkFileMagicNumber(MultipartFile file, String extension) {
byte[] expectedMagicNumber = ALLOWED_FILE_TYPES.get(extension);
if (expectedMagicNumber == null) {
if (expectedMagicNumber == null || expectedMagicNumber.length == 0) {
return true;
}
try (InputStream is = file.getInputStream()) {
byte[] actualBytes = new byte[expectedMagicNumber.length];
int offset = 0;
int len = expectedMagicNumber.length;
while (offset < len) {
int read = is.read(actualBytes, offset, len - offset);
if (read == -1) {
return false;
}
offset += read;
}
return Arrays.equals(actualBytes, expectedMagicNumber);
} catch (IOException e) {
log.error("读取文件魔数失败, fileName:{}, error:{}", file.getOriginalFilename(), e.getMessage());
return false;
}
byte[] actualMagicNumber = Arrays.copyOf(fileBytes, expectedMagicNumber.length);
return Arrays.equals(actualMagicNumber, expectedMagicNumber);
}
@PostMapping("/deleteFile")
......@@ -220,7 +243,7 @@ public class CommonController {
aliOssUtil.delete(url);
return Result.success();
}catch (Exception e){
log.error("文件删除失败:{}",e);
log.error("文件删除失败, url:{}, error:{}", url, e.getMessage(), e);
}
return Result.fail().setMsg("文件删除失败");
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment