|
| 1 | +package com.mdtalalwasim.fileproject2.service.impl; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.nio.file.Files; |
| 5 | +import java.util.Optional; |
| 6 | + |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.stereotype.Service; |
| 9 | +import org.springframework.web.multipart.MultipartFile; |
| 10 | + |
| 11 | +import com.mdtalalwasim.fileproject2.entity.FileData; |
| 12 | +import com.mdtalalwasim.fileproject2.repository.FileDataRepository; |
| 13 | +import com.mdtalalwasim.fileproject2.service.FileDataService; |
| 14 | + |
| 15 | +@Service |
| 16 | +public class FileDataServiceImpl implements FileDataService{ |
| 17 | + |
| 18 | + @Autowired |
| 19 | + private FileDataRepository fileDataRepository; |
| 20 | + |
| 21 | + //private final String FILE_PATH = "/home/wasim/git/springboot-file-project-upload-file-directly-in-directory-folder/springboot-file-project-upload-file-directly-in-directory-folder/uploads/"; |
| 22 | + private final String FILE_PATH = "/home/wasim/git/springboot-file-project-upload-file-directly-in-directory-folder/springboot-file-project-upload-file-directly-in-directory-folder/uploads/"; |
| 23 | + |
| 24 | + @Override |
| 25 | + public String uploadFileToFileDirectory(MultipartFile file) throws IOException { |
| 26 | + String filePath = FILE_PATH+file.getOriginalFilename();//absolute path |
| 27 | + // TODO Auto-generated method stub |
| 28 | + FileData fileData = fileDataRepository.save(FileData.builder() |
| 29 | + .name(file.getOriginalFilename()) |
| 30 | + .type(file.getContentType()) |
| 31 | + .filePath(filePath).build()); |
| 32 | + |
| 33 | + //copy your file into that particular path |
| 34 | + file.transferTo(new java.io.File(filePath)); |
| 35 | + |
| 36 | + if(fileData!= null) { |
| 37 | + return "file uploaded successfully : "+file.getOriginalFilename()+ " and Files uploaded path is :"+filePath; |
| 38 | + } |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public byte[] downloadFileFromFileDirectory(String fileName) throws IOException { |
| 44 | + // TODO Auto-generated method stub |
| 45 | + |
| 46 | + |
| 47 | + Optional<FileData> fileDataObj = fileDataRepository.findByName(fileName); |
| 48 | + |
| 49 | + //first need to get the file path |
| 50 | + String filePath = fileDataObj.get().getFilePath(); |
| 51 | + |
| 52 | + //got the file, now decompress it. |
| 53 | + byte[] imageFile = Files.readAllBytes(new java.io.File(filePath).toPath()); |
| 54 | + |
| 55 | + return imageFile; |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments