Skip to content

File upload download

Download Local

@GetMapping("/download-local")
    public ResponseEntity<Resource> downloadFile() {

        // Load file as Resource
        Resource resource;

        String file = "C:\\temp\\Wilde Six Sigma draft 3.pptx";
        try {
            Path filePath = Paths.get(file).normalize();
            resource = new UrlResource(filePath.toUri());
        } catch (MalformedURLException e) {
            // Handle file not found or other exceptions
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }

        // Check if file exists and is readable
        if (!resource.exists() || !resource.isReadable()) {
            return ResponseEntity.notFound().build();
        }

        // Set Content-Disposition header to force download
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        // Set Content-Type header based on file type
        MediaType mediaType;
        try {
            mediaType = MediaType.parseMediaType(resource.getFile().toURI().toURL().openConnection().getContentType());
        } catch (IOException e) {
            e.printStackTrace();
            mediaType = MediaType.APPLICATION_OCTET_STREAM;
        }

        return ResponseEntity.ok()
                .contentType(mediaType)
                .headers(headers)
                .body(resource);
    }

Download from remote api

@GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam(name = "remoteFilePath") String remoteFilePath) {

        log.info("Request received for file ({})", remoteFilePath);

        return sharePointService.downloadFileFromEndPoint(sharePointUrl, Paths.get(remoteFilePath), token);
    }
public ResponseEntity<Resource> downloadFileFromEndPoint(String url, Path remoteFilePath, String token) {
        // Create HttpHeaders with appropriate authentication, if needed
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);

        String endPoint = 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 Resource
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Resource> responseEntity = restTemplate.exchange(
                endPoint,
                HttpMethod.GET,
                new HttpEntity<>(headers),
                Resource.class);

        // Check if the request was successful
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            // Set appropriate headers for file download
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + remoteFilePath.getFileName().toString() + "\"");

            // Set Content-Type header based on file type, if known
            responseHeaders.setContentType(responseEntity.getHeaders().getContentType());

            // Return ResponseEntity with Resource and headers
            return ResponseEntity.ok()
                    .headers(responseHeaders)
                    .body(responseEntity.getBody());
        } else {
            // Handle error responses from SharePoint API
            // You can return an appropriate error ResponseEntity
            return ResponseEntity.status(responseEntity.getStatusCode()).build();
        }
    }

Upload to local

@PostMapping("/upload-local")
    public String handleFileUploadToLocal(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                file.transferTo(new File("C:/temp/" + file.getOriginalFilename()));
                return "File uploaded successfully!";
            } catch (IOException e) {
                e.printStackTrace();
                return "Failed to upload file!";
            }
        } else {
            return "File is empty!";
        }
    }

Upload to external api

@PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("directory") String directory) {
        try {
            return sharePointService.uploadFileToEndpoint(file, sharePointUrl, directory, token);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
public ResponseEntity<String> uploadFileToEndpoint(MultipartFile file, String url, String folder, String token) throws IOException {


        String endpointUrl = url + UrlUtils.encodeURLPathComponent(String.format("/_api/web/GetFolderByServerRelativeUrl('%s')/Files/add(url='%s',overwrite=true)", folder, file.getOriginalFilename()));

        log.info("Uploading file to {}", endpointUrl);

        HttpHeaders headers = new HttpHeaders();
        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 file
        InputStream inputStream = file.getInputStream();
        InputStreamResource resource = new InputStreamResource(inputStream);


//            HttpEntity<ByteArrayResource> requestEntity = new HttpEntity<>(resource, headers);
        HttpEntity<InputStreamResource> requestEntity = new HttpEntity<>(resource, headers);

        ResponseEntity<String> response = restTemplate.exchange(endpointUrl, HttpMethod.POST, requestEntity, String.class);

        // Handle response as needed
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("File uploaded successfully");
        } else {
            log.debug("Error uploading file: " + response.getStatusCode());
        }


        return response;
    }

Comments