0% found this document useful (0 votes)
5 views3 pages

Api 1

The document outlines a file upload service that validates folder names, file sizes, and MIME types before storing files. It restricts uploads to specific file formats (images and PDFs) and enforces a maximum file size of 5MB. The service logs successful uploads and creates necessary directories if they do not exist.

Uploaded by

n22dcat016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Api 1

The document outlines a file upload service that validates folder names, file sizes, and MIME types before storing files. It restricts uploads to specific file formats (images and PDFs) and enforces a maximum file size of 5MB. The service logs successful uploads and creates necessary directories if they do not exist.

Uploaded by

n22dcat016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

@Value("${hoidanit.upload-file.

uri-path}")
private String baseUri;

private static final Logger logger = LoggerFactory.getLogger(YourClass.class);

public String storeFile(MultipartFile file, String folder) throws IOException,


URISyntaxException {
// Kiểm tra tên folder hợp lệ
if (folder.contains("..") || folder.contains("/") || folder.contains("\\")) {
throw new StorageException("Invalid folder name");
}

// Loại bỏ ký tự đặc biệt khỏi tên tệp


String sanitizedFileName = file.getOriginalFilename().replaceAll("[^a-zA-Z0-
9\\.\\-]", "_");

// Kiểm tra kích thước file


long maxSize = 5 * 1024 * 1024; // 5MB
if (file.getSize() > maxSize) {
throw new StorageException("File size exceeds the limit of 5MB.");
}

// Kiểm tra MIME type


String mimeType = Files.probeContentType(file.getResource().getFile().toPath());
if (mimeType == null || !mimeType.startsWith("image/") && !
mimeType.equals("application/pdf")) {
throw new StorageException("Invalid file type.");
}

// Tạo đường dẫn file


String fileName = System.currentTimeMillis() + "-" + sanitizedFileName;
URI uri = URI.create(baseUri + folder + "/" + fileName);
Path filePath = Paths.get(uri);

// Ghi file
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
}

logger.info("File uploaded successfully: " + fileName);


return fileName;
}

@ApiMessage("Upload single file")


@GetMapping("/files")
public ResponseEntity<ResponseFileDTO> uploadFile(
@RequestParam(name = "file", required = false) MultipartFile file,
@RequestParam("folder") String folder) throws StorageException, IOException,
URISyntaxException {

if (file == null || file.isEmpty()) {


throw new StorageException("File is empty");
}

String name = file.getOriginalFilename();


List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "pdf");
boolean isValid = allowedExtensions.stream().anyMatch(allowedExtension ->
name.endsWith(allowedExtension));

if (!isValid) {
throw new StorageException("Invalid file format. Only " +
allowedExtensions.toString() + " are allowed.");
}

// Tạo thư mục nếu chưa tồn tại


this.fileService.createUploadFolder(baseUri + folder);

// Lưu tệp
String fileName = this.fileService.storeFile(file, folder);
return ResponseEntity.ok(new ResponseFileDTO(fileName, Instant.now()));
}

You might also like