@GetMapping("/download-local")publicResponseEntity<Resource>downloadFile(){// Load file as ResourceResourceresource;Stringfile="C:\\temp\\Wilde Six Sigma draft 3.pptx";try{PathfilePath=Paths.get(file).normalize();resource=newUrlResource(filePath.toUri());}catch(MalformedURLExceptione){// Handle file not found or other exceptionse.printStackTrace();returnResponseEntity.notFound().build();}// Check if file exists and is readableif(!resource.exists()||!resource.isReadable()){returnResponseEntity.notFound().build();}// Set Content-Disposition header to force downloadHttpHeadersheaders=newHttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\""+resource.getFilename()+"\"");// Set Content-Type header based on file typeMediaTypemediaType;try{mediaType=MediaType.parseMediaType(resource.getFile().toURI().toURL().openConnection().getContentType());}catch(IOExceptione){e.printStackTrace();mediaType=MediaType.APPLICATION_OCTET_STREAM;}returnResponseEntity.ok().contentType(mediaType).headers(headers).body(resource);}
@GetMapping("/download")publicResponseEntity<Resource>downloadFile(@RequestParam(name="remoteFilePath")StringremoteFilePath){log.info("Request received for file ({})",remoteFilePath);returnsharePointService.downloadFileFromEndPoint(sharePointUrl,Paths.get(remoteFilePath),token);}
publicResponseEntity<Resource>downloadFileFromEndPoint(Stringurl,PathremoteFilePath,Stringtoken){// Create HttpHeaders with appropriate authentication, if neededHttpHeadersheaders=newHttpHeaders();headers.add("Authorization","Bearer "+token);StringendPoint=url+UrlUtils.encodeURLPathComponent(String.format("/_api/web/GetFolderByServerRelativeUrl('%s')/Files('%s')/$value",remoteFilePath.getParent().toString(),remoteFilePath.getFileName().toString()));log.info("Fetching from URL: {}",endPoint);// Make a request to SharePoint API to get the file as a ResourceRestTemplaterestTemplate=newRestTemplate();ResponseEntity<Resource>responseEntity=restTemplate.exchange(endPoint,HttpMethod.GET,newHttpEntity<>(headers),Resource.class);// Check if the request was successfulif(responseEntity.getStatusCode()==HttpStatus.OK){// Set appropriate headers for file downloadHttpHeadersresponseHeaders=newHttpHeaders();responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\""+remoteFilePath.getFileName().toString()+"\"");// Set Content-Type header based on file type, if knownresponseHeaders.setContentType(responseEntity.getHeaders().getContentType());// Return ResponseEntity with Resource and headersreturnResponseEntity.ok().headers(responseHeaders).body(responseEntity.getBody());}else{// Handle error responses from SharePoint API// You can return an appropriate error ResponseEntityreturnResponseEntity.status(responseEntity.getStatusCode()).build();}}
@PostMapping("/upload-local")publicStringhandleFileUploadToLocal(@RequestParam("file")MultipartFilefile){if(!file.isEmpty()){try{file.transferTo(newFile("C:/temp/"+file.getOriginalFilename()));return"File uploaded successfully!";}catch(IOExceptione){e.printStackTrace();return"Failed to upload file!";}}else{return"File is empty!";}}
publicResponseEntity<String>uploadFileToEndpoint(MultipartFilefile,Stringurl,Stringfolder,Stringtoken)throwsIOException{StringendpointUrl=url+UrlUtils.encodeURLPathComponent(String.format("/_api/web/GetFolderByServerRelativeUrl('%s')/Files/add(url='%s',overwrite=true)",folder,file.getOriginalFilename()));log.info("Uploading file to {}",endpointUrl);HttpHeadersheaders=newHttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentLength(file.getSize());headers.add("Authorization","Bearer "+token);// Get the bytes of the file content// byte[] fileBytes = file.getBytes();// ByteArrayResource resource = new ByteArrayResource(fileBytes);// Open an input stream from the fileInputStreaminputStream=file.getInputStream();InputStreamResourceresource=newInputStreamResource(inputStream);// HttpEntity<ByteArrayResource> requestEntity = new HttpEntity<>(resource, headers);HttpEntity<InputStreamResource>requestEntity=newHttpEntity<>(resource,headers);ResponseEntity<String>response=restTemplate.exchange(endpointUrl,HttpMethod.POST,requestEntity,String.class);// Handle response as neededif(response.getStatusCode()==HttpStatus.OK){log.info("File uploaded successfully");}else{log.debug("Error uploading file: "+response.getStatusCode());}returnresponse;}