Здесь я загружаю файл в путь к папке, который я указал в Application.properties
это местоположение c, но я хочу изменить это местоположение на Dynami c, потому что для другого пациента я хочу загрузить файлы в разные каталоги на основе идентификатора.
package com.emr.service;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.emr.config.FileStorageProperties;
import com.emr.exception.FileStorageException;
import com.emr.exception.UploadedFileNotFoundException;
import com.emr.model.Patient;
import com.emr.model.PatientDocs;
import com.emr.repository.PatientDocsRepository;
@Service
public class FileStorageServiceImpl implements FileStorageService {
private static final Logger LOGGER = LogManager.getLogger(FileStorageServiceImpl.class);
@Autowired
PatientDocsRepository patientDocsRepository;
// private final Path fileStorageLocation;
private Path fileStorageLocation;
@Autowired
public FileStorageServiceImpl(FileStorageProperties fileStorageProperties) {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.",
ex);
}
}
@Override
public PatientDocs storeFile(MultipartFile file, Integer patientId) {
// Normalize file name
String f = Integer.toString(patientId);
Path path = Paths.get(file+f);
if (!Files.exists(path)) {
try {
Files.createDirectory(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Directory created");
} else {
System.out.println("Directory already exists");
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String fileName = "P_" + patientId + "_Dt_" + dateFormat.format(date) + "_"
+ StringUtils.cleanPath(file.getOriginalFilename());
// this.fileStorageLocation= Paths.get(fileStorageLocation+"/"+f);
System.out.println(fileStorageLocation);
try {
// Check if the file's name contains invalid characters
if (fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/docs/downloadFile/")
.path(fileName).toUriString();
PatientDocs docs = new PatientDocs();
Patient patient = new Patient();
patient.setPatientId(patientId);
docs.setPatient(patient);
docs.setFileDownloadUri(fileDownloadUri);
docs.setFileType(file.getContentType());
docs.setSize(file.getSize());
docs.setDateCreated(date);
docs = patientDocsRepository.save(docs);
return docs;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
@Override
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new UploadedFileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new UploadedFileNotFoundException("File not found " + fileName, ex);
}
}
}
Как я могу изменить путь к динамическому c местоположению? Может кто-нибудь подсказать мне с правильным кодом!