
Java Spring Boot Rest API to Upload/Download File on Server
diseinuak4web.netred;
diseinuak4web.netce;
diseinuak4web.netource;
diseinuak4web.nete;
diseinuak4web.netUtils;
diseinuak4web.netartFile;
diseinuak4web.nettFoundException;
diseinuak4web.netption;
diseinuak4web.netmedURLException;
diseinuak4web.net;
diseinuak4web.net;
diseinuak4web.net;
diseinuak4web.netrdCopyOption;
publicclassDocumentStorageService {
privatefinalPathfileStorageLocation;
@Autowired
DocumentStoragePropertiesRepodocStorageRepo;
@Autowired
publicDocumentStorageService(DocumnentStoragePropertiesfileStorageProperties) {
diseinuak4web.netorageLocation=diseinuak4web.net(diseinuak4web.netoadDir())
.toAbsolutePath().normalize();
try {
diseinuak4web.netDirectories(diseinuak4web.netorageLocation);
} catch (Exceptionex) {
thrownewDocumentStorageException("Could not create the directory where the uploaded files will be stored.", ex);
}
publicStringstoreFile(MultipartFilefile, IntegeruserId, StringdocType) {
// Normalize file name
StringoriginalFileName=diseinuak4web.netath(diseinuak4web.netginalFilename());
StringfileName="";
try {
// Check if the file's name contains invalid characters
if(diseinuak4web.netns("..")) {
thrownewDocumentStorageException("Sorry! Filename contains invalid path sequence "+originalFileName);
}
StringfileExtension="";
try {
fileExtension=diseinuak4web.neting(diseinuak4web.netdexOf("."));
} catch(Exceptione) {
fileExtension="";
}
fileName=userId+"_"+docType+fileExtension;
// Copy file to the target location (Replacing existing file with the same name)
PathtargetLocation=diseinuak4web.nete(fileName);
diseinuak4web.net(diseinuak4web.netutStream(), targetLocation, diseinuak4web.netE_EXISTING);
DocumnentStoragePropertiesdoc=diseinuak4web.netocumentByUserId(userId, docType);
if(doc!=null) {
diseinuak4web.netumentFormat(diseinuak4web.nettentType());
diseinuak4web.neteName(fileName);
diseinuak4web.net(doc);
} else {
DocumnentStoragePropertiesnewDoc=newDocumnentStorageProperties();
diseinuak4web.netrId(userId);
diseinuak4web.netumentFormat(diseinuak4web.nettentType());
diseinuak4web.neteName(fileName);
diseinuak4web.netumentType(docType);
diseinuak4web.net(newDoc);
}
returnfileName;
} catch (IOExceptionex) {
thrownewDocumentStorageException("Could not store file "+fileName+". Please try again!", ex);
}
publicResourceloadFileAsResource(StringfileName) throwsException {
-
-