1

I need to develop a REST API endpoint to serve a file. So I implement the following code with help of other resources

  @GetMapping(path = Array("/download"))
  def downloadFile() : ResponseEntity[Resource] = {
    var file: File = new File("src/main/scala/testFile.txt")
    if(file.exists()){
      val path = Paths.get(file.getAbsolutePath)
      val resource = new InputStreamResource(new FileInputStream(file))
//      val resource = new ByteArrayResource(Files.readAllBytes(path))
      val responseHeaders = new HttpHeaders();
      responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=results.txt")
      responseHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate")
      responseHeaders.add("Pragma", "no-cache")
      responseHeaders.add("Expires", "0")
      println(resource)
      ResponseEntity.ok()
        .headers(responseHeaders)
        .contentLength(file.length())
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .body(resource);

    }else{
      ResponseEntity.notFound().build()
    }
  }

and also from react side implemented as below

  var win = window.open('_blank');
  var filePath = ".../download"
  downloadFile(filePath, function (blob) {
    var url = URL.createObjectURL(blob);
    win.location = url;
  });




function downloadFile(url, success) {
  
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (success) success(xhr.response);
    }
  };
  xhr.send(null);
}

the exception is coming from the scala side it throws

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class org.springframework.core.io.InputStreamResource] with preset Content-Type 'application/octet-stream']

any suggestions for fix this issue. thank you

Dulanga Heshan
  • 1,335
  • 1
  • 19
  • 36
  • 1
    [this question](https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers) is related to yours. – zmerr Aug 23 '21 at 14:14
  • 1
    you question is also related to [this one](https://stackoverflow.com/questions/35680932/download-a-file-from-spring-boot-rest-service) – zmerr Aug 23 '21 at 14:16

0 Answers0