0

I'm trying to download a PDF from my local machine. Everything is fine, but an error occurs while returning the resource. Please give clarity about a classcast exception and the proper solution to fix this.

My controller

@PostMapping("downloadDocuments")
public ResponseEntity<Resource> downloadDocuments(@RequestBody String postData)
        throws ServiceException, IOException {
    return iMasterService.downloadDocumentFromFilePathAndFileName(postData);
}

My service class

public ResponseEntity<Resource> downloadDocumentFromFilePathAndFileName(String fileName) throws ServiceException {

    File file = null;

    File templetDocsFolderPath = new File(relativeFilePathRenderer.getTemplateDocsFolderPath());
    /* templateDocsFolderPath : C:/home/uploads/templatedocs/ */
    if (!templetDocsFolderPath.exists()) {
        Util.createDirictory(templetDocsFolderPath);
    }
    file = new File(templetDocsFolderPath + File.separator + fileName);//fileName : sample.pdf
    /*file : C:/home/uploads/templatedocs/sample.pdf */
    HttpHeaders headers = getHttpHeaders(file);
    InputStreamResource resource = null;
    try {
        resource = new InputStreamResource(new FileInputStream(file));
        System.out.println("resource :"+resource.exists());//true
    } catch (Exception e) {
        throw new ServiceException("Document not available");
    }

    return ResponseEntity.ok().headers(headers).contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/pdf")).body(resource);//"application/octet-stream" /*Error Occur on this return area*/
}

The error

java.lang.ClassCastException: class org.springframework.core.io.InputStreamResource cannot be cast to class java.lang.String (org.springframework.core.io.InputStreamResource is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')

Akoram
  • 3
  • 5

0 Answers0