|
| 1 | +package it.fabioformosa.quartzmanager.services; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import org.springframework.beans.factory.annotation.Value; |
| 5 | +import org.springframework.stereotype.Service; |
| 6 | +import org.springframework.web.multipart.MultipartFile; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.nio.file.Path; |
| 10 | +import java.nio.file.Paths; |
| 11 | + |
| 12 | +@Slf4j |
| 13 | +@Service |
| 14 | +public class FileService { |
| 15 | + String uploadsDirectory; |
| 16 | + public FileService(@Value("${chista-scheduler.uploadFolder}") String uploadsDirectory) { |
| 17 | + this.uploadsDirectory = uploadsDirectory; |
| 18 | + createUploadsFolderIfNotExists(); |
| 19 | + } |
| 20 | + |
| 21 | + public String getUploadsDirectory() { |
| 22 | + return this.uploadsDirectory; |
| 23 | + } |
| 24 | + |
| 25 | + public void uploadFile(MultipartFile file) throws Exception { |
| 26 | + if (file.isEmpty()) { |
| 27 | + throw new Exception("Please select a file to upload"); |
| 28 | + } |
| 29 | + // Get the file's original name |
| 30 | + String originalFileName = file.getOriginalFilename(); |
| 31 | + |
| 32 | + // Construct the path where you want to save the file |
| 33 | + Path filePath = Paths.get(uploadsDirectory, originalFileName); |
| 34 | + |
| 35 | + // Save the file to the specified location |
| 36 | + file.transferTo(filePath.toFile()); |
| 37 | + } |
| 38 | + |
| 39 | + private void createUploadsFolderIfNotExists() { |
| 40 | + File uploadDir = new File(uploadsDirectory); |
| 41 | + if (!uploadDir.exists()) { |
| 42 | + uploadDir.mkdir(); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments