Home > Back-end >  how to download file from a file server in spring boot
how to download file from a file server in spring boot

Time:10-14

I uploaded a file using multipart successfully and appended the entity class id to it. Sending a get request returns a null value.

This is my post endpoint:

@PostMapping("/{id}/upload_multiple")
public ResponseEntity<ResponseMessage> createDocument(@PathVariable Long id,
        @RequestParam("applicationLetter") MultipartFile appLetter,
        @RequestParam("certificateOfInc") MultipartFile cInc, @RequestParam("paymentReceipt") MultipartFile payment,
        @RequestParam("taxClearance") MultipartFile tax, @RequestParam("staffsResume") MultipartFile staffs,
        @RequestParam("letterOfCredibility") MultipartFile credibility,
        @RequestParam("workCertificate") MultipartFile workCert,
        @RequestParam("consentAffidavit") MultipartFile affidavit,
        @RequestParam("collaborationCert") MultipartFile colabo, @RequestParam("directorsId") MultipartFile idcard,
        @RequestParam("membership") MultipartFile member) throws IOException {

    documentService.create(id, appLetter, cInc, payment, tax, staffs, credibility, workCert, affidavit, colabo,
            idcard, member);
    String message = "Upload successful";

    return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
}

uploaded files are saved in a another folder 10001 which is the ID of the document entity. My challenge now is to get those files from 10001 folder. uploaded

This is what I tried but is returning null value for all the documents:

@GetMapping( "/files/{filename:. }/{id}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = documentService.load(filename);
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""   file.getFilename()   "\"")
            .body(file);
}

My service class:

private final Path root = Paths.get("documents");

 @Override
  public Resource load(String filename) {
    try {
      Path file = root.resolve(filename);
      Resource resource = new UrlResource(file.toUri());

      if (resource.exists() || resource.isReadable()) {
        return resource;
      } else {
        throw new RuntimeException("Could not read the file!");
      }
    } catch (MalformedURLException e) {
      throw new RuntimeException("Error: "   e.getMessage());
    }
  }

CodePudding user response:

refer this example :

  @GetMapping("/files")
  public ResponseEntity<List<ResponseFile>> getListFiles() {
    List<ResponseFile> files = storageService.getAllFiles().map(dbFile -> {
      String fileDownloadUri = ServletUriComponentsBuilder
          .fromCurrentContextPath()
          .path("/files/")
          .path(dbFile.getId())
          .toUriString();

      return new ResponseFile(
          dbFile.getName(),
          fileDownloadUri,
          dbFile.getType(),
          dbFile.getData().length);
    }).collect(Collectors.toList());

    return ResponseEntity.status(HttpStatus.OK).body(files);
  }

  @GetMapping("/files/{id}")
  public ResponseEntity<byte[]> getFile(@PathVariable String id) {
    FileDB fileDB = storageService.getFile(id);

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""   fileDB.getName()   "\"")
        .body(fileDB.getData());
  }

CodePudding user response:

Try this method for loading resource. to see if it works

Resource file = fileStorageService.loadFileAsResource(fileName);

CodePudding user response:

Try this code

@GetMapping( "/files/{filename:. }/{id}")
public void getFile(@PathVariable String filename, HttpServletRequest request, final HttpServletResponse response) {
    BufferedInputStream bufferedInputStream = null;
    try {
        File file = ...;

        response.setHeader("Cache-Control", "must-revalidate");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-disposition", "attachment; ");

        bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(bufferedInputStream, response.getOutputStream());

    } catch (Exception e) {
    logger.error(e.getMesssage(), e);
    } finally {
        try {
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception ex) {
            logger.error(ex);
        }

        try {
            if (bufferedInputStream != null)
                bufferedInputStream.close();
        } catch (Exception ex) {
            logger.error(ex);
        }
    }
}

I'm not sure it will work with your system, but for me I still use this method to download files normally.

  • Related