|
|
@@ -17,6 +17,7 @@ import java.io.IOException;
|
|
|
import java.io.InputStream;
|
|
|
import java.net.URLConnection;
|
|
|
import java.text.SimpleDateFormat;
|
|
|
+import java.util.Arrays;
|
|
|
import java.util.Base64;
|
|
|
import java.util.Date;
|
|
|
|
|
|
@@ -32,24 +33,38 @@ public class FileUploadController {
|
|
|
@PostMapping("/file")
|
|
|
public String uploadFile(@RequestParam("file") MultipartFile file,
|
|
|
@RequestParam(value = " ", required = false) String path) {
|
|
|
- if (path == null) {
|
|
|
- String basePath = "application";
|
|
|
- try {
|
|
|
- basePath = file.getContentType().split("/")[0];
|
|
|
- } catch (Exception ignored) {
|
|
|
+ if (!file.isEmpty() && isValidFileType(file)) {
|
|
|
+
|
|
|
+ if (path == null) {
|
|
|
+ String basePath = "application";
|
|
|
+ try {
|
|
|
+ basePath = file.getContentType().split("/")[0];
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ }
|
|
|
+ path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
|
|
|
+ + RandomStringUtils.randomAlphabetic(8)
|
|
|
+ + "." + FilenameUtils.getExtension(file.getOriginalFilename());
|
|
|
+ // 清洗文件名以防止注入攻击
|
|
|
+ path = sanitizePath(path);
|
|
|
}
|
|
|
- path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
|
|
|
- + RandomStringUtils.randomAlphabetic(8)
|
|
|
- + "." + FilenameUtils.getExtension(file.getOriginalFilename());
|
|
|
- }
|
|
|
- InputStream is;
|
|
|
- try {
|
|
|
- is = file.getInputStream();
|
|
|
- } catch (IOException e) {
|
|
|
- log.error("上传失败", e);
|
|
|
- throw new BusinessException("上传失败", e.getMessage());
|
|
|
+ try (InputStream is = file.getInputStream()) {
|
|
|
+ return storageService.uploadFromInputStream(is, path);
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error("上传失败", e);
|
|
|
+ throw new BusinessException("上传失败", e.getMessage());
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ throw new BusinessException("无效的文件");
|
|
|
}
|
|
|
- return storageService.uploadFromInputStream(is, path);
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean isValidFileType(MultipartFile file) {
|
|
|
+ String[] allowedTypes = {"image/jpeg", "image/png"};
|
|
|
+ return Arrays.stream(allowedTypes).anyMatch(type -> type.equals(file.getContentType()));
|
|
|
+ }
|
|
|
+
|
|
|
+ private String sanitizePath(String path) {
|
|
|
+ return path.replaceAll("[^A-Za-z0-9\\./-]", "");
|
|
|
}
|
|
|
|
|
|
@PostMapping("/base64")
|
|
|
@@ -66,7 +81,7 @@ public class FileUploadController {
|
|
|
} catch (Exception ignored) {
|
|
|
}
|
|
|
path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
|
|
|
- + RandomStringUtils.randomAlphabetic(8) + ext;
|
|
|
+ + RandomStringUtils.randomAlphabetic(8) + ext;
|
|
|
}
|
|
|
InputStream is;
|
|
|
try {
|