Add image upload validations and random naming

This commit is contained in:
Tim
2025-07-01 13:00:47 +08:00
parent a37f046898
commit d69f7251e0
5 changed files with 43 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ package com.openisle.controller;
import com.openisle.model.User;
import com.openisle.service.ImageUploader;
import com.openisle.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -20,6 +21,12 @@ public class UserController {
private final UserService userService;
private final ImageUploader imageUploader;
@Value("${app.upload.check-type:true}")
private boolean checkImageType;
@Value("${app.upload.max-size:5242880}")
private long maxUploadSize;
@GetMapping("/me")
public ResponseEntity<UserDto> me(Authentication auth) {
User user = userService.findByUsername(auth.getName()).orElseThrow();
@@ -29,6 +36,12 @@ public class UserController {
@PostMapping("/me/avatar")
public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file,
Authentication auth) {
if (checkImageType && (file.getContentType() == null || !file.getContentType().startsWith("image/"))) {
return ResponseEntity.badRequest().body(Map.of("error", "File is not an image"));
}
if (file.getSize() > maxUploadSize) {
return ResponseEntity.badRequest().body(Map.of("error", "File too large"));
}
String url = null;
try {
url = imageUploader.upload(file.getBytes(), file.getOriginalFilename()).join();

View File

@@ -12,6 +12,7 @@ import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -52,15 +53,22 @@ public class CosImageUploader extends ImageUploader {
@Override
public CompletableFuture<String> upload(byte[] data, String filename) {
return CompletableFuture.supplyAsync(() -> {
String ext = "";
int dot = filename.lastIndexOf('.');
if (dot != -1) {
ext = filename.substring(dot);
}
String randomName = UUID.randomUUID().toString().replace("-", "") + ext;
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(data.length);
PutObjectRequest req = new PutObjectRequest(
bucketName,
filename,
randomName,
new ByteArrayInputStream(data),
meta);
cosClient.putObject(req);
return baseUrl + "/" + filename;
return baseUrl + "/" + randomName;
}, executor);
}
}